1

I have a list in R (data) which has list[[1]]....list[[6]] and I would like to apply a t.test on each list I did this but it didnt work for me :

ttest <- for(i in 1:length(data)){
    var1 <- data[[i]][5:6]
    var2<- data[[i]][7:8]
    t <- t.test(var1,var2)
}
ttest

can someone gives me an idea how to do it as a loop?

4
  • Do you have data.frame as list elements? Try lapply(data, function(x) t.test(x[5:6], x[7:8]))
    – akrun
    Jun 30, 2015 at 10:50
  • As there are multiple list elements, you need to assign the results to a list with length equal to the length of the data (in your for loop). i.e. t1 <- vector('list', length(data)); for(i in ....)....; t1[[i]] <- t.test(var1, var2)}
    – akrun
    Jun 30, 2015 at 10:55
  • Did it worked for you?
    – akrun
    Jun 30, 2015 at 12:01
  • Does this answer your question? doing t.test for columns for each row in data set May 13, 2020 at 21:28

1 Answer 1

0

You can try

lapply(data, function(x) t.test(x[5:6], x[7:8]))

Or a modification of the for loop by allocating the results to a list 't1'

t1 <- vector('list', length(data))
for(i in 1:length(data)){
     var1 <- data[[i]][5:6]
     var2<- data[[i]][7:8]
  t1[[i]] <- t.test(var1,var2)
 }

 t1

data

set.seed(24)
data <- lapply(1:3, function(i) as.data.frame(matrix(sample(0:9, 
              20*10, replace=TRUE), ncol=10)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.