开发者

Anova, for loop to apply function

开发者 https://www.devze.com 2023-03-19 00:06 出处:网络
>str(set) \'data.frame\':1000 obs. of6 variables: $ ID: Factor .. $ a : Factor .. $ b: Factor .. $ c: Factor ..
>str(set)
'data.frame':   1000 obs. of  6 variables:
$ ID       : Factor ..
$ a : Factor ..
$ b: Factor ..
$ c: Factor ..
$ dat    : num  ..
$ contrasts : Ord.factor ..


>X
[1] "a"  "b" "c" 


for (i in 1 :length(X) ){
  my=X[i]
  f=as.formula(paste("dat~contrasts*", paste(my,"Error(ID/(contrasts))",sep="+")))
  sum = summary( aov (f, data =set))
}

X can be very huge, so was thinking about an apply function instead of for-loop.Is it possible in this case??

I tried this:

apply(
  as.matrix(X), 1, function(i){
    summary(aov(as.formula(paste("dat~contrasts*",
      paste(i, "Error(ID/(contrasts))"开发者_StackOverflow中文版, sep="+"))), data=set))
  }
)

But this makes no sense. Can anyone help me?


This ought to do it:

# Sample data
set <- data.frame(ID=1:10, a=letters[1:10], b=LETTERS[1:10], c=letters[10:1],
                  dat=runif(10), contrasts=ordered(rep(1:2, 5)))
X <- letters[1:3] # a,b,c

sapply(X, function(my) {
  f <- as.formula(paste("dat~contrasts*",my,"+Error(ID/(contrasts))"))
  summary(aov(f, data=set))
}, simplify=FALSE)

Note the use of sapply with simplify=FALSE. Using lapply also works, but it doesn't add names to the list components.

0

精彩评论

暂无评论...
验证码 换一张
取 消