Creating a list of functions from a character vector

Thanks in advance, and I'm sorry if this question was answered earlier - I looked pretty wide. I have a data set containing a string with concatenated information, in particular: name, color code, some function expression. For example, a single value might be:

Cost # FF0033 @ magazine (x) +6.

I have all the code to extract the information, and I get a vector of expressions that I would like to convert to a list of actual functions.

For instance:

func.list <- list()
test.func <- c("x","x+1","x+2","x+3","x+4")

where test.func is the expression vector. I would like to:

func.list[[3]]

To be equivalent

function(x){x+3}

I know that I can create a function using:

somefunc <- function(x){eval(parse(text="x+1"))} 

to convert the value of a character to a function. The problem occurs when I try to execute a loop to make several functions. For an example of what I tried, this did not work:

for(i in 1:length(test.func)){
  temp <- test.func[i]
  f <- assign(function(x){eval(expr=parse(text=temp))})
  func.list[[i]] <- f
}

(http://stats.stackexchange.com/questions/3836/how-to-create-a-vector-of-functions), :

makefunc <- function(y){y;function(x){y}}
for(i in 1:length(test.func)){
   func.list[[i]] <-  assign(x=paste("f",i,sep=""),value=makefunc(eval(parse(text=test.func[i]))))
 }

: eval (expr, envir, enc): 'x'

- j- j- data.frame, script , , .

+5
3

, , , :

foo <- function(x){x+3}
> body(foo) <- quote(x+4)
> foo
function (x) 
x + 4

, , , , - :

body(foo) <- parse(text = "x+5")
+3

joran , - :

test.data <- matrix(data=rep(1,25),5,5)
test.data <- data.frame(test.data)

test.func <- c("x","x+1","x+2","x+3","x+4")
func.list <- list()

for(i in 1:length(test.func)){
  func.list[[i]] <- function(x){}
  body(func.list[[i]]) <- parse(text=test.func[i])
}

processed <- mapply(do.call,func.list,lapply(test.data,list))

, joran.

+2

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)
+1
source

All Articles