[R] group by in data.frame

Ivan Calandra ivan.calandra at uni-hamburg.de
Fri Feb 25 13:04:22 CET 2011


Hi,

I think ave() might do what you want:
df <- data.frame(a=rep(c("this","that"),5), b1=rnorm(10), b2=rnorm(10))
ave(df[,2], df[,1], FUN=mean)

For all columns, you could do that:
d <- lapply(df[,2:3], FUN=function(x)ave(x,df[,1],FUN=mean))
df2 <- cbind(df, d)

HTH,
Ivan

Le 2/25/2011 12:11, zem a écrit :
> Hi all,
>
> i have a little problem, and i think it is really simple to solve, but i
> dont know exactly how to.
> here is the "challange":
> i have a data.frame with n colum, i have to group 2 of them and calculate
> the mean value of the 3. one. so far so good, that was easy - i used
> aggregate function to do this:
> group<-aggregate(x[,1],list(x[,2],x[,3]),mean)
> and now i have to copy the calculated mean value to every row of the
> date.frame (in a new column in the dataframe), ofcourse by copying should be
> the value  adequate to the group
>
> it will be great if someone can help me
> thanx in advance!

-- 
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Abt. Säugetiere
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de

**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/1525_8_1.php



More information about the R-help mailing list