How would I do something like this: f <- function(x, g) { s <- as.character(g) # THIS DOES NOT WORK sprintf("The %s of x is %.0f\n", s, g(x)) } f(c(2,3,4), "median") f(c(2,3,4), "mean") and get the results "The median of x is 3" "The mean of x is 3" -- Ajay Shah http://www.mayin.org/ajayshah ajayshah at mayin.org http://ajayshahblog.blogspot.com <*(:-? - wizard who doesn't know the answer.
Gabor Grothendieck
2009-Oct-17 17:37 UTC
[R] How do I access with the name of a (passed) function
Try this:> show.name <- function(x) deparse(substitute(x)) > show.name(pi)[1] "pi" On Sat, Oct 17, 2009 at 7:26 AM, Ajay Shah <ajayshah at mayin.org> wrote:> How would I do something like this: > > f <- function(x, g) { > ?s <- as.character(g) ? ? ? ? ? ? ? # THIS DOES NOT WORK > ?sprintf("The %s of x is %.0f\n", s, g(x)) > } > > f(c(2,3,4), "median") > f(c(2,3,4), "mean") > > and get the results > > ? "The median of x is 3" > ? "The mean of x is 3" > > -- > Ajay Shah ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?http://www.mayin.org/ajayshah > ajayshah at mayin.org ? ? ? ? ? ? ? ? ? ? ? ? ? ? http://ajayshahblog.blogspot.com > <*(:-? - wizard who doesn't know the answer. > > ______________________________________________ > R-help at r-project.org 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. >
Duncan Murdoch
2009-Oct-18 11:53 UTC
[R] How do I access with the name of a (passed) function
On 17/10/2009 7:26 AM, Ajay Shah wrote:> How would I do something like this: > > f <- function(x, g) { > s <- as.character(g) # THIS DOES NOT WORK > sprintf("The %s of x is %.0f\n", s, g(x)) > }Gabor showed you how to do it if you pass an expression which evaluates to a function. If you want to pass an expression that returns a character string as below, use if (is.character(g)) { s <- g g <- get(s, parent.frame()) # gets it from the caller's frame }> > f(c(2,3,4), "median") > f(c(2,3,4), "mean") > > and get the results > > "The median of x is 3" > "The mean of x is 3" >Duncan Murdoch