I have a vector of functions which I want to evaluate on the same number.
Example:
c=1
functions=c(x^2,2*x,x/2)
(evaluate each function at c=1)
Desired output: c(1,2,0.5)
Which function would be the best to do this besides using a loop?
CodePudding user response:
as a one-off shorthand, you could use an anonymous function:
c = 1
(\(x) c(x^2, 2*x, x/2))(x = c)
CodePudding user response:
Please avoid declaring c as a variable, as it is also the name of a most common function c().
Functions can not be stored in vectors,but can be stored in lists. We can loop through the list to call all functions with the desired value as a variable.
my_value <- 1
my_functions <- list(square = function(x) x^2,
dbl = function(x) 2*x,
half = function(x) x/2)
sapply(my_functions, \(x) x(my_value))
square dbl half
1.0 2.0 0.5
If we do not want names in the desired output, we can unname() it:
sapply(my_functions, \(x) x(my_value)) |>
unname()
[1] 1.0 2.0 0.5
