Søren Højsgaard
2007-Aug-22 14:09 UTC
[R] Evaluating f(x(2,3)) on a function f<- function(a,b){a+b}
Dear list 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. Regards Søren [[alternative HTML version deleted]]
Paul Smith
2007-Aug-22 14:16 UTC
[R] Evaluating f(x(2,3)) on a function f<- function(a,b){a+b}
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
Gabor Grothendieck
2007-Aug-22 14:19 UTC
[R] Evaluating f(x(2,3)) on a function f<- function(a,b){a+b}
Try this: do.call(f, as.list(x)) On 8/22/07, S?ren H?jsgaard <Soren.Hojsgaard at agrsci.dk> wrote:> Dear list > 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. > > Regards > S?ren > > > [[alternative HTML version deleted]] > > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > >