Skip to content

Instantly share code, notes, and snippets.

@alaiacano
Created April 25, 2012 13:54
Show Gist options
  • Save alaiacano/2489881 to your computer and use it in GitHub Desktop.
Save alaiacano/2489881 to your computer and use it in GitHub Desktop.
Passing variables to plyr
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")
@alaiacano
Copy link
Author

SOLUTION (thanks Hadley):

ddply(df.in, c(f1, f2), summarize,
         value=sum(value)
         )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment