Passing a list of functions to ddply in R

Benjamin Scott Corwin

I want to able to apply a list of function to ddply so that the list can expand based on what I want.

Something like this:

func_list = list(Start.Date = "min(Date)", End.Date = "max(Date)")
do.call(ddply, c(list(.data = df, .variables = grps, .fun=summarize), func_list))

When I run that, it calls ddply but then has a variable called Start.Date that equals the string "min(Date)". I've tried not quoting, but that doesn't work either.

Edit (example code and desired results):

library(plyr)

get_summary <- function(grps, func_list, df = raw) {    
    out <- do.call(ddply,
                   c(list(.data = df, .variables = grps, .fun=summarize),
                     func_list))
    return(out)
}

raw <- data.frame(date = c(as.Date("2015-5-1"),
                           as.Date("2015-5-1"),
                           as.Date("2015-5-2"),
                           as.Date("2015-5-2")),
                  count = c(2,4,6,8),
                  amnt = c(100,200,300,400))

func_list <- list(
    total_count = "sum(count)",
    avg_amnt = "mean(amnt)"
)

get_summary("date", func_list)

# Desired output:
#         date total_count avg_amnt
# 1 2015-05-01           6      150
# 2 2015-05-02          14      350
#
# Which is equivalent to:
# ddply(raw, "date", summarize, total_count = sum(count), avg_amnt = mean(amnt))
Molx

To fix your code you only need parse():

func_list <- list(
          total_count = parse(text="sum(count)"),
          avg_amnt = parse(text="mean(amnt)"))

This will tell the interpreter that the text should be evaluated as code and not as strings.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related