r - Using a 'complex' function within the apply family -


i attempting use aov() function within tapply() line, , not sure if not possible, or if i'm coding incorrectly.

factors<-c("factor 1", "factor 2") years<-c("year 1", "year 2", "year 3","year 4", "year 5") width<-rnorm(100) height<-rnorm(100)  mydata<-data.frame(years,factors,width,height) 

i see if there difference between factor levels each year. note real data has several factor levels, why i'm using anova , not t-test.

i can tapply() 'simple' functions, sum:

with(mydata,tapply(width,factors,fun="sum")) 

from simple examples, think way tapply() works subsets data 2nd entry, factors, takes first entry, width, , put's whatever function declared. reasoning, tried:

with(mydata,tapply(width~factors,years,fun="aov")) 

this returns error arguments must have same length.

if possible use tapply function requires complex input, how go doing this? , anticipate problems how store such output. example, if have 2 anova's saved, save them single 'variable name'.

width.anova<-with(mydata,aov(width~factors)) height.anova<-with(mydata,aov(height~factors))  all.anovas<-c(width.anova, height.anova) 

what able along lines of (*following code not work, there show i'm getting at):

#all.anovas$width.anova 

clearly c() function not work. know able use $ syntax, should using data frame, following not work:

all.anovas<-data.frame(width.anova, height.anova) 

if there simpler way of getting result i'm looking for, tips on appreciated. again, i'm looking 5 anovas - comparing difference between factor levels 1 , 2 each of 5 years. in reality, data has 8 years , 5 factor levels. doing these anova's on several variables (like width, , height) well.

you're using wrong function. want more this:

lapply(split(mydata,mydata$years),function(x) aov(width ~ factors,data = x)) 

or use plyr package , this:

dlply(mydata,.(years),function(x) aov(width ~ factors,data = x)) 

tapply working vectors, typically, more complex objects you'll want different tool.

to address comment, perhaps this:

aov_fun <- function(x,vars){     out <- vector("list",length(vars))     names(out) <- vars     f <- paste0(vars,"~factors")     (i in seq_along(vars)){         out[[i]] <- aov(as.formula(f[i]),data = x)     }     out }  lapply(split(mydata,mydata$years),aov_fun,vars = c('width','height')) 

Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -