I'm trying to iteratively generate some functions using a For Loop:
# Create a list to hold the functions
funcs <- list()
funcs[]
# loop through to define functions
for(i in 1:21){
# Make function name
funcName <- paste( 'func', i, sep = '' )
# make function
func = function(x){x * i}
funcs[[funcName]] = func
}
However, it's not working as I hoped as the i value is not being evaluated within each function. I want to try and define the function to equal x * 1; x * 2; etc, but what I end up with is a function that is x * i; where i is 21.
I tried using the eval() function and that just resulted in x * eval(i) being st开发者_运维知识库ored.
Use a closure (a function that write functions):
multiply <- function(i) {
force(i)
function(x) x * i
}
funcs <- list()
for(i in 1:21){
funcName <- paste( 'func', i, sep = '' )
funcs[[funcName]] = multiply(i)
}
# OR in one line, with lapply
funcs <- lapply(1:21, multiply)
Check this one:
# Create a list to hold the functions
funcs <- list()
funcs[]
# loop through to define functions
for(i in 1:21){
# Make function name
funcName <- paste( 'func', i, sep = '' )
# make function
func = paste('function(x){x * ', i,'}',sep = '')
funcs[[funcName]] = eval(parse(text=func))
}
精彩评论