Getting a function name as a string

后端 未结 8 1275
半阙折子戏
半阙折子戏 2020-12-01 03:18

Say I have a bunch of functions, each with something likeMyFunction.1, etc. I want to pass these functions into another function, which prints out a small repo

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 03:52

    Another approach would be to pass the names of the functions into your report function, and then get the functions themselves with the get() command. For instance:

    function.names <- c("which","all")
    fun1 <- get(function.names[1])
    fun2 <- get(function.names[2])
    

    Then you have the names in your original character vector, and the functions have new names as you defined them. In this case, the all function is now being called as fun2:

    > fun2(c(TRUE, FALSE))
    [1] FALSE
    

    Or, if you really want to keep the original function names, just assign them locally with the assign function:

    assign(function.names[2], get(function.names[2]))
    

    If you run this command right now, you will end up with the all function in your ".GlobalEnv". You can see this with ls().

提交回复
热议问题