R: how to evaluate a function over components of a given vector

Viewed 36

One the one hand I have a function which has the components of a vector as arguments. This function is like this one:

y_fun = function( x1, x2, x3, x4 ) 2*x1 + x2*x3*log( x4 )

On the other hand I do not have the components

x1, x2, x3, x4

but, only the vector (with these components) given by:

vect = c(x1, x2, x3, x4)

It is not very practical for my purpose to type in, one after the other, the values of the vector's components into the arguments of the function. How is it possible to evaluate the function over the elements of a given vector? I tried this (without success):

y_fun( as.list( vect ) )

and this

elements = noquote( paste0( vect, collapse = ",") )

y_fun( elements )

1 Answers

We may use do.call

do.call(y_fun, as.list(vect))
[1] 2

The vect is created as unnamed vector. It works for this case, but it may be better to have as named vector in case the function have many arguments and the ones passed in vect are not in the same order

vect <- c(x1 = x1, x2 = x2, x3 = x3, x4 = x4)

Or simply a named list

lst1 <- list(x1 = x1, x2 = x2, x3 = x3, x4 = x4)
do.call(y_fun, lst1)
Related