user352188
user352188

Reputation: 53

R: passing one value to a vector of functions

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?

Upvotes: 0

Views: 41

Answers (2)

GuedesBF
GuedesBF

Reputation: 9878

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

Upvotes: 1

user18309711
user18309711

Reputation:

as a one-off shorthand, you could use an anonymous function:

c = 1
(\(x) c(x^2, 2*x, x/2))(x = c)

Upvotes: 1

Related Questions