Search code examples
rfunctionapplyevaluatesapply

Evaluate many functions using one data in R


I know that I can evaluate one function with many data using apply, but can I evaluate many functions using one data? Using sapply i can get:

sapply(list(1:5,10:20,5:18), sum)

but I want somethnig like this:

sapply(1:5, list(sum, min,max))

and get

15 1 5

Any clever idea? :)


Solution

  • Swap the argument order, since you are looping over the functions not the data.

    sapply(list(sum, min, max), function(f) f(1:5))
    

    The two most preferred modern approaches for calculating summary statistics use the dplyr and data.table packages. dplyr has a variety of solutions (only working with data frames, not vectors) using summarise or summarise_each.

    library(dplyr)
    data <- data.frame(x = 1:5)
    summarise(data, min = min(x), max = max(x), sum = sum(x))
    summarise_each(data, funs(min, max, sum))
    

    The dplyr-idiomatic style is to construct expressions using chaining.

    data %>%
     summarise(min = min(x), max = max(x), sum = sum(x))
    data %>%
      summarise_each(funs(min, max, sum))
    

    For programmatic use (as opposed to interactive use), underscore-suffixed functions and formulae are recommended for non-standard evaluation.

    data %>%
     summarise_(min = ~ min(x), max = ~ max(x), sum = ~ sum(x))
    data %>%
      summarise_each_(funs_(c("min", "max", "sum"), "x")
    

    See agstudy's answer for the data.table solution.