4
>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))", sep="+"))), data=set))
  }
)

But this makes no sense. Can anyone help me?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Jasmine
  • 149
  • 3
  • 7
  • 3
    If `X` is a vector then `sapply` is more appropriate, but this in essence is just a nicer way to write your for loop, it will not actually speed your code up. – Sacha Epskamp Jul 08 '11 at 07:40
  • 1
    @Ashley : Nice you put the str() information, but it would be even nicer if you gave us some toy dataset to play around with. See also http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Joris Meys Jul 08 '11 at 08:49

1 Answers1

3

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.

Tommy
  • 39,997
  • 12
  • 90
  • 85
  • @ashley: If the answer was what you need, you should mark is as an answer. You should also upvote answers (and questions) you like. Just click on the score in the upper left. – Tommy Jul 12 '11 at 20:14