[R] how calculate mean for each group

Spencer Graves spencer.graves at pdf.com
Thu Oct 2 15:47:52 CEST 2003


An alternative to renaming columns in the ouput of aggregate is to 
provide names in the "by" list as follows: 

aggregate(df$treatment, list(gp=df$group, dup=df$duplicate), mean)

hope this helps.  spencer graves

Marc Schwartz wrote:

>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
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>  
>




More information about the R-help mailing list