Ning Ma
2009-Nov-02 04:07 UTC
[R] How to execute a funcition which name is stored in a string?
Hi, everybody Is there any way to execute a function, which name is stored in a string. such as: a <- "ls()" foo(a) ## same as ls() itself. Or, to execute a R command, which is stored in a string such as: a <- "m1 <- matrix(1:9,3,3)" foo(a) ## same as the assignment itself
David Winsemius
2009-Nov-02 04:43 UTC
[R] How to execute a funcition which name is stored in a string?
On Nov 1, 2009, at 11:07 PM, Ning Ma wrote:> Hi, everybody > > Is there any way to execute a function, which name is stored in a > string. > such as: > a <- "ls()" > foo(a) ## same as ls() itself.Need to leave the "()" off. > fstr <- "sum" > eval(parse(text=fstr))(1:5) [1] 15> > Or, to execute a R command, which is stored in a string > such as: > a <- "m1 <- matrix(1:9,3,3)" > foo(a) ## same as the assignment itself> eval(parse(text="m1 <- matrix(1:9,3,3)")) > m1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 -- David Winsemius, MD Heritage Laboratories West Hartford, CT
Charlie Sharpsteen
2009-Nov-02 06:58 UTC
[R] How to execute a funcition which name is stored in a string?
On Sun, Nov 1, 2009 at 8:07 PM, Ning Ma <pningma at gmail.com> wrote:> > Hi, everybody > > Is there any way to execute a function, which name is stored in a string. > such as: > a <- "ls()" > foo(a) ## same as ls() itself.One way to accomplish this by using get() to search for a function that matches your string. You can assign the return value of get() to a variable which may be used like the original function object: a <- 'ls' foo <- get( a, mode = 'function' ) foo() [1] "a" ? ? ? ? ?"foo" -Charlie