Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For-loop to create vector of mean differences in t-tests

Let’s say I have

set.seed(1)
e <- data.frame(tti = log2(runif(200)),
                corona = c(rep("Corona", 100), rep("Before", 100)),
                type = rep(c("A", "B", "C", "D")))

I am comparing mean differences between tti (time to treatment initiation on log2-scale) before and during COVID-19 for each e$type (here n=4 but many more in my dataset). I want to apply a for loop for this repetitive task, but I am quite new to this and frankly stock at the moment.

My current attempt:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for(i in unique(e$type)){
 m <- c(
   round(1-2^(unique(t.test(e$tti[e$type == i] ~ e$corona[e$type == i])$estimate[2]) - 
                unique(t.test(e$tti[e$type == i] ~ e$corona[e$type == i])$estimate[1])),
         digits = 3)*100
 )
}

However, this attempt only return one value.

Expected output:
m should be a vector containing the four estimates of mean differences

> m
24.7  10.5  1.5  28.7

How can this be done?

>Solution :

You could do:

m <- c()
for(i in unique(e$type)){
 m[i] <- c(
   round(1-2^(unique(t.test(e$tti[e$type == i] ~ e$corona[e$type == i])$estimate[2]) - 
                unique(t.test(e$tti[e$type == i] ~ e$corona[e$type == i])$estimate[1])),
         digits = 3)*100
 )
}

This initializes m and then fills it during the loop. That should give you all 4 results in one vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading