Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 461
bartektartanus Avatar asked Jul 18 '13 10:07

bartektartanus


People also ask

Can you combine functions in R?

Concatenating Objects in R Programming – combine() Function Moreover, combine() function is used to combine factors in R programming.

What is the difference between Lapply and Sapply in R?

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.

What does Lapply do in R?

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.


2 Answers

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.

like image 160
Richie Cotton Avatar answered Sep 29 '22 13:09

Richie Cotton


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
like image 30
Simon O'Hanlon Avatar answered Sep 29 '22 14:09

Simon O'Hanlon