Question

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? :)

Was it helpful?

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.

OTHER TIPS

You can evaluate many functions on many data. Just use an anonymous function like this:

sapply( list(1:5,10:20,5:18), function(x) c( Sum = sum(x) , Min = min(x) , Max = max(x) ) )
#    [,1] [,2] [,3]
#Sum   15  165  161
#Min    1   10    5
#Max    5   20   18

Using summarize from plyr:

library(plyr)
summarize(data.frame(x=1:5),min=min(x),max=max(x),sum=sum(x))
  min max sum
1   1   5  15

Or using data.table

library(data.table)
data.table(x=1:5)[,list(min=min(x),max=max(x),sum=sum(x))]
  min max sum
1:   1   5  15

Here's another we can add to the pot. Nice for working with large lists.

funs <- list(sum = sum, min = min, max = max)
Map(function(f, ...) f(...),  funs, list(x = 1:15))
# $sum
# [1] 120
#
# $min
# [1] 1
#
# $max
# [1] 15
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top