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

前端 未结 3 939
长发绾君心
长发绾君心 2020-12-08 04:02

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

E.g.

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

[[2]]
sin

works:

3条回答
  •  悲&欢浪女
    2020-12-08 04:53

    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
    

提交回复
热议问题