[R] Evaluating f(x(2,3)) on a function f<- function(a,b){a+b}

Paul Smith phhs80 at gmail.com
Wed Aug 22 16:16:17 CEST 2007


On 8/22/07, Søren Højsgaard <Soren.Hojsgaard at agrsci.dk> wrote:
> I have a function and a vector, say
>     f <- function(a,b){a+b}
>     x <- c(2,3)
> I want to "evaluate f on x" in the sense of computing f(x[1],x[2]). I would like it to be so that I can write f(x). (I know I can write a wrapper function g <- function(x){f(x[1],x[2])}, but this is not really what I am looking for). Is there a general way doing this (programmatically)? (E.g. by "unpacking" the elements of x and putting them in the "right places" when calling f...)
> I've looked under formals, alist etc. but so far without luck.

I hope that the following helps:

> f <- function(x) {sum(x)}
> f(c(2,3))
[1] 5
> f(c(2,3,5))
[1] 10
>

Paul



More information about the R-help mailing list