Created
April 25, 2012 13:54
-
-
Save alaiacano/2489881 to your computer and use it in GitHub Desktop.
Passing variables to plyr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my.reduce <- function(df.in, f1, f2){ | |
x <- ddply(df.in, .(f1, f2), summarize, | |
value=sum(value) | |
) | |
x | |
} | |
df <- data.frame( | |
state=rep(c("MA", "NY", "CA"), each=10), | |
year=rep((2001:2010), 3), | |
other=sample(c("A", "B", "C", "D"), 30, replace=TRUE), | |
value = runif(30) | |
) | |
# state year other value | |
# 1 MA 2001 C 0.6021182 | |
# 2 MA 2002 B 0.5948861 | |
# 3 MA 2003 A 0.7402534 | |
# 4 MA 2004 A 0.8149549 | |
# 5 MA 2005 A 0.2495546 | |
# 6 MA 2006 B 0.4370473 | |
# I would like these two lines to return the same result. | |
ddply(df, .(state, other), summarize, value=sum(value)) | |
my.reduce(df, "state", "other") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SOLUTION (thanks Hadley):