Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function using the character string of the function name in R?

Tags:

r

I am trying to call a function with a given string of the function name.

E.g.

print(funcList) [[1]] `*`  [[2]] sin 

works:

mult <- `*` mult(5,6) [1] 30 

doesn't work:

func1 <- funcList[[1]] func1(5,6)  func2 <- funcList[[2]] func2(1.2) 

So is it possible to call all of the functions in the functionList?

like image 501
tObi Avatar asked Jun 19 '11 17:06

tObi


People also ask

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you access characters in a string in R?

To get access to the individual characters in an R string, you need to use the substr function: str = 'string' substr(str, 1, 1) # This evaluates to 's'. For the same reason, you can't use length to find the number of characters in a string. You have to use nchar instead.

How do you call a function in a string variable?

Use the Variable Method to Call a Function From a String Stored in a Variable in PHP. In PHP, we can also store the functions in variables. The function name should be assigned to a variable as a string, and then we can call the function a variable.


2 Answers

Those don't look like strings; that looks like a list of functions. To answer the question posed in your title, see get(). For example, using your list but stored as character strings:

funcList <- list("*", "sin") 

we can use get() to return the function with name given by the selected element of the list:

> f <- get(funcList[[1]]) > f function (e1, e2)  .Primitive("*") > f(3,4) [1] 12 

An alternative is the match.fun() function, which given a string will find a function with name matching that string:

> f2 <- match.fun(funcList[[1]]) > f2(3,4) [1] 12 

but as ?match.fun tells us, we probably shouldn't be doing that at the prompt, but from within a function.

If you do have a list of functions, then one can simply index into the list and use it as a function:

> funcList2 <- list(`*`, sin) > str(funcList2) List of 2  $ :function (e1, e2)    $ :function (x)   > funcList2[[1]](3, 4) [1] 12 > funcList2[[2]](1.2) [1] 0.9320391 

or you can save the functions out as interim objects, but there is little point in doing this:

> f3 <- funcList2[[1]] > f3(3,4) [1] 12 > f4 <- funcList2[[2]] > f4(1.2) [1] 0.9320391 
like image 145
Gavin Simpson Avatar answered Oct 08 '22 12:10

Gavin Simpson


See documentation for do.call.

A quick demonstration:

do.call("rnorm", list(100, 0, 1)) 

first parameter can be a string literal, or R object, and the second one is list of arguments that are to be matched with provided function formal arguments.

like image 23
aL3xa Avatar answered Oct 08 '22 12:10

aL3xa