[R] How to use a string to refer a function?

Don MacQueen macq at llnl.gov
Fri Feb 12 00:12:52 CET 2010

Don't really understand what you have in mind, but maybe this will do it.

f <- function(x=3) x^2

Now, if I want to "get" the function f, given that I only know its 
name "f", I can do this:

getf <- get('f')


Or even:

>  get('f')(5)
[1] 25


>  attributes(getf)
[1] "function(x=3) x^2"

At 4:26 PM -0600 2/11/10, blue sky wrote:
>  > f=function(){ print('in f')}
>>  attr(f, 'source')
>[1] "function(){ print('in f')}"
>I have the above simple function. I can use the variable f to refer to
>the function and get the function source.
>Suppose that I have 'f' as a string (say I get it from ls()), could
>somebody let me know how to get the function from the name 'f'?
>R-help at r-project.org mailing list
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA

More information about the R-help mailing list