[R] how calculate mean for each group

Marc Schwartz MSchwartz at medanalytics.com
Thu Oct 2 04:38:33 CEST 2003


On Wed, 2003-10-01 at 20:15, szhan at uoguelph.ca wrote:
> Hello, R experts:
> I got data like this:
> group   duplicate   treatment 
> A         Y          5
> A         Y          3
> A         N          6
> B         Y          2
> B         N          4
> B         Y          1
> How to sort the data and calculate the average treatment value for each group 
> in two level of duplicate. Results like this:
> group   duplicate   treatment 
> A         Y          4
> A         N          6
> B         Y          1.5
> B         N          4
> Thank you in advance.
> 
> Josh


# Create a dataframe
df <- data.frame(group = c(rep("A", 3), rep("B", 3)), 
                 duplicate = c("Y", "Y", "N", "Y", "N", "Y"), 
                 treatment = c(5, 3, 6, 2, 4, 1))

# Use aggregate
aggregate(df$treatment, list(df$group, df$duplicate), mean)
  Group.1 Group.2   x
1       A       N 6.0
2       B       N 4.0
3       A       Y 4.0
4       B       Y 1.5

Aggregate returns a data frame in this case, so that you can then set
the colnames and order the output if you wish.

HTH,

Marc Schwartz




More information about the R-help mailing list