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