djq*_*djq 3 statistics for-loop r function
我正在尝试使用For循环迭代生成一些函数:
# 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
}
Run Code Online (Sandbox Code Playgroud)
但是,它并没有像我希望的那样工作,因为在每个函数中没有评估i值.我想尝试将函数定义为等于x*1; x*2; 等等,但我最终得到的是一个x*i的函数; 我21岁的地方.
我尝试使用eval()函数,只是导致x*eval(i)被存储.
使用闭包(写函数的函数):
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)
Run Code Online (Sandbox Code Playgroud)