# [R] averaging rows on a data.frame according to a factor

arun smartpink111 at yahoo.com
Sat Nov 23 00:46:06 CET 2013

```Hi,

dat<-as.data.frame(cbind(c("a","a","a","b","b"), c(1,2,3,3,2),c(4,3,5,4,4)))
str(dat)
#'data.frame':    5 obs. of  3 variables:
# \$ V1: Factor w/ 2 levels "a","b": 1 1 1 2 2
# \$ V2: Factor w/ 3 levels "1","2","3": 1 2 3 3 2
# \$ V3: Factor w/ 3 levels "3","4","5": 2 1 3 2 2

#better way would be
dat<-data.frame(V1=c("a","a","a","b","b"), V2=c(1,2,3,3,2),V3=c(4,3,5,4,4))
str(dat)
#'data.frame':    5 obs. of  3 variables:
# \$ V1: Factor w/ 2 levels "a","b": 1 1 1 2 2
# \$ V2: num  1 2 3 3 2
# \$ V3: num  4 3 5 4 4

library(plyr)
ddply(dat,.(V1),colwise(mean))

#or
aggregate(.~V1,data=dat,mean)

A.K.

On Friday, November 22, 2013 5:45 PM, john d <dobzhanski at gmail.com> wrote:
Dear all,

I apologize for the newbie question, but I'm stuck.

I have a data frame in the following form:

dat<-as.data.frame(cbind(c("a","a","a","b","b"), c(1,2,3,3,2),c(4,3,5,4,4)))

I need a way to generate a new dataframe with the average for each factor.
The result should look like:

res<-as.data.frame(cbind(c("a","b"), c(2,2.5),c(4,4)))

Any help would be greatly appreciated.

Jonathan

[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help