Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

summarize all numeric columns of data frame by group in R

I have a data frame that has unique groups defined by 3 character variables

catvars <- c("DATE", "COUNTRY_FULL_NAME", "TENOR")

The rest of the data frame consists of 20 numeric variables (condensing it to 3 in the sample below)

numvars <- c("X1", "Y1, "Z1")

I am trying to create a new data frame with the mean for each numeric variable calculates by group

For a single variable, I can use ddply from the plyr package:

DFsum <- ddply(DF, catvars, summarize, X1mean = mean(X, na.rm=TRUE))

But I can't figure out how to modify this ddply command to include all numeric variables. Any suggestions? Thank you

like image 309
ec0n0micus Avatar asked Jun 06 '14 20:06

ec0n0micus


1 Answers

I think you're looking for numcolwise?

ddply(diamonds,.(cut),numcolwise(mean,na.rm = TRUE))
        cut     carat    depth    table    price        x        y        z
1      Fair 1.0461366 64.04168 59.05379 4358.758 6.246894 6.182652 3.982770
2      Good 0.8491847 62.36588 58.69464 3928.864 5.838785 5.850744 3.639507
3 Very Good 0.8063814 61.81828 57.95615 3981.760 5.740696 5.770026 3.559801
4   Premium 0.8919549 61.26467 58.74610 4584.258 5.973887 5.944879 3.647124
5     Ideal 0.7028370 61.70940 55.95167 3457.542 5.507451 5.520080 3.401448
like image 111
joran Avatar answered Sep 28 '22 07:09

joran