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

Time:11-25

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:

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?

CodePudding user response:

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.

  • Related