Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply many functions to one vector

Tags:

r

apply

I am looking for an option to apply many functions to one vector. I think it is kind on an inverse apply function where one function is applied to many vectors (or columns).

Is there a way of specifing two or more functions (like mean and max) and apply this on a vector?

like image 784
jnshsrs Avatar asked Jun 22 '15 11:06

jnshsrs


People also ask

How do I apply multiple functions to a list in R?

The lapply () and sapply () functions can be used for performing multiple functions on a list in R. This function is used in order to avoid the usage of loops in R. The difference between both the functions is the sapply () function does the same job as lapply () function but returns a vector.

Can you have a vector of functions?

A vector function is a function that takes one or more variables and returns a vector. We'll spend most of this section looking at vector functions of a single variable as most of the places where vector functions show up here will be vector functions of single variables.

What is Mapply?

mapply is a multivariate version of sapply . mapply applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on. Arguments are recycled if necessary.

How does Mapply work in R?

mapply function in R The mapply() function is a multivariate apply of sorts which applies a function in parallel over a set of arguments. lapply()iterate over a single R object but What if you want to iterate over multiple R objects in parallel then mapply() is the function for you.


1 Answers

Similar to @CathG's comment, but without get:

v <- rnorm(10)
funs <- list(mean, median, sd) 
sapply(funs, function(fun, x) fun(x), x = v)

Or with do.call:

sapply(funs, do.call, args = list(v))
like image 196
Roland Avatar answered Sep 24 '22 10:09

Roland