Create a list of functions from a vector of characters

后端 未结 3 1476
醉酒成梦
醉酒成梦 2021-01-12 08:12

Thanks in advance, and sorry if this question has been answered previously - I have looked pretty extensively. I have a dataset containing a row of with concatenated informa

3条回答
  •  爱一瞬间的悲伤
    2021-01-12 09:06

    This is what I do:

    f <- list(identity="x",plus1 = "x+1", square= "x^2")
    funCreator <- function(snippet){
      txt <- snippet
      function(x){
        exprs <- parse(text = txt)
        eval(exprs)   
      }
    }
    listOfFunctions <- lapply(setNames(f,names(f)),function(x){funCreator(x)}) # I like to have some control of the names of the functions
    listOfFunctions[[1]] # try to see what the actual function looks like?
    library(pryr)
    unenclose(listOfFunctions[[3]]) # good way to see the actual function http://adv-r.had.co.nz/Functional-programming.html
    # Call your funcions
    listOfFunctions[[2]](3) # 3+1 = 4
    do.call(listOfFunctions[[3]],list(3)) # 3^2 = 9
    attach(listOfFunctions) # you can also attach your list of functions and call them by name
    square(3)  # 3^2 = 9
    identity(7) # 7 ## masked object identity, better detach it now!
    detach(listOfFunctions)
    

提交回复
热议问题