R apply function on groups of data frame

622 Views Asked by At

I need to run ANOVA on each subject individually. I have a dataframe consists of data coming from 37 subjects and I don't want to loop 37 times to run ANOVA separately 37 times on each subject. These are the first 4 rows of my data:

        latency subject     trialcode
   1    1385    14233664    neighbour
   2    2493    14233664    neighbour
   3    1429    14233664    neighbour
   4    1884    14233664    neighbour

This is my code:

 tmp <- with(as.data.frame(data),
        by(data$subject,
           function(x) aov(latency ~ trialcode + Error(trialcode), data=data)))
 sapply(tmp, coef)

But I get an error message :

Error in unique.default(x, nmax = nmax) : 

unique() applies only to vectors

Any help appreciated Thanks

1

There are 1 best solutions below

0
On

I think the by call is not correct. If I use data(npk)

do.call(rbind,by(npk[,-1], npk$block,
      FUN=function(x) coef(aov(yield~N+P+K, data=x))))

For your data, it might be

do.call(rbind, by(data[,-2], data$subject, 
     FUN=function(x) coef(aov(latency ~ trialcode+ Error(trialcode), x))))

Or using data.table

library(data.table)
setkey(setDT(data), subject)[, as.list(coef(aov(latency~trialcode+
           Error(trialcode))),by=subject]