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?

jas
  • 13
  • 3
  • Do you have data.frame as list elements? Try `lapply(data, function(x) t.test(x[5:6], x[7:8]))` – akrun Jun 30 '15 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 '15 at 10:55
  • Did it worked for you? – akrun Jun 30 '15 at 12:01
  • Does this answer your question? [doing t.test for columns for each row in data set](https://stackoverflow.com/questions/28119894/doing-t-test-for-columns-for-each-row-in-data-set) – Karolis Koncevičius May 13 '20 at 21:28

1 Answers1

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)))
akrun
  • 874,273
  • 37
  • 540
  • 662