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? :)
Concatenating Objects in R Programming – combine() Function Moreover, combine() function is used to combine factors in R programming.
The lapply() function in R can be used to apply a function to each element of a list, vector, or data frame and obtain a list as a result. The sapply() function can also be used to apply a function to each element of a list, vector, or data frame but it returns a vector as a result.
The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.
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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With