Evaluate many functions using one data in R -
i know can evaluate 1 function many data using apply, can evaluate many functions using 1 data? using sapply can get:
sapply(list(1:5,10:20,5:18), sum)
but want somethnig this:
sapply(1:5, list(sum, min,max))
and get
15 1 5
any clever idea? :)
swap argument order, since looping on functions not data.
sapply(list(sum, min, max), function(f) f(1:5))
the 2 preferred modern approaches calculating summary statistics use dplyr
, data.table
packages. dplyr
has variety of solutions (only working 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 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 interactive use), underscore-suffixed functions , formulae recommended 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 data.table
solution.
Comments
Post a Comment