简体   繁体   English

如何使用R中函数名的字符串调用函数?

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

I am trying to call a function with a given string of the function name. 我试图用函数名称的给定字符串调用函数。

Eg 例如

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? 那么可以调用functionList中的所有函数吗?

Those don't look like strings; 那些看起来不像字符串; that looks like a list of functions. 看起来像一个功能列表。 To answer the question posed in your title, see get() . 要回答标题中提出的问题,请参阅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: 我们可以使用get()返回列表中所选元素给出的名称的函数:

> 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: 另一种方法是match.fun()函数,给定一个字符串将找到一个名称与该字符串匹配的函数:

> 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. 但正如?match.fun告诉我们的那样,我们可能不应该在提示符处这样做,而是在函数内部。

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

See documentation for do.call . 请参阅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. 第一个参数可以是字符串文字或R对象,第二个参数是要与提​​供的函数形式参数匹配的参数列表。

you could also use match.fun 你也可以使用match.fun

> functionlist <- list("*","sin")
> f <- match.fun(functionlist[[1]])
> f(5,6)
[1] 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM