Re: [R] Using apply to get group means

2009-03-31 Thread David Winsemius
That is precisely the reason for the existence of the ave function. Using Wickham's example: > x1 <- rep(c("A", "B", "C"), 3) > x2 <- c(rep(1, 3), rep(2, 3), 1, 2, 1) > x3 <- c(1, 2, 3, 4, 5, 6, 2, 6, 4) > df <- data.frame(x1, x2, x3) > df$grpx3 <- ave(df$x3, list(x1,x2)) > df x1 x2 x3 grpx

Re: [R] Using apply to get group means

2009-03-31 Thread Domenico Vistocco
Sorry, there was a mistake in the previous mail: Domenico Vistocco wrote: A different solution (using aggregate for the table of means and merge for adding it to the dataframe): x1<-rep(c("A","B","C"),3) x2<-c(rep(1,3),rep(2,3),1,2,1) x3<-c(1,2,3,4,5,6,2,6,4) x<-data.frame(x1,x2,x3) #here usi

Re: [R] Using apply to get group means

2009-03-31 Thread Domenico Vistocco
A different solution (using aggregate for the table of means and merge for adding it to the dataframe): x1<-rep(c("A","B","C"),3) x2<-c(rep(1,3),rep(2,3),1,2,1) x3<-c(1,2,3,4,5,6,2,6,4) x<-data.frame(x1,x2,x3) #here using data.frame the x1 variable is directly converted to factor x3means <-

Re: [R] Using apply to get group means

2009-03-31 Thread hadley wickham
On Tue, Mar 31, 2009 at 11:31 AM, baptiste auguie wrote: > Not exactly the output you asked for, but perhaps you can consider, > > library(doBy) >> summaryBy(x3~x2+x1,data=x,FUN=mean) >> >>  x2 x1 x3.mean >> 1  1  A     1.5 >> 2  1  B     2.0 >> 3  1  C     3.5 >> 4  2  A     4.0 >> 5  2  B     5.

Re: [R] Using apply to get group means

2009-03-31 Thread baptiste auguie
Not exactly the output you asked for, but perhaps you can consider, library(doBy) > summaryBy(x3~x2+x1,data=x,FUN=mean) x2 x1 x3.mean 1 1 A 1.5 2 1 B 2.0 3 1 C 3.5 4 2 A 4.0 5 2 B 5.5 6 2 C 6.0 the plyr package also provides similar functionality, as do t

[R] Using apply to get group means

2009-03-31 Thread Alan Cohen
Hi all, I'm trying to improve my R skills and make my programming more efficient and succinct. I can solve the following question, but wonder if there's a better way to do it: I'm trying to calculate mean by several variables and then put this back into the original data set as a new variable