我想在函数内动态分配变量。例如,我想使用...
s
calc_recruits <- function(SSB, stored_rec_funs, ...){
rec <- mapply(function(stored_rec_funs, SSB, ...){stored_rec_funs(SSB, ...)}, SSB=SSB, stored_rec_funs=stored_rec_funs, ...=...)
return(rec)
}
如果我有
rec_BH <- function(SSB, a, b, ...){
SSB <- SSB/1e9 # SSB in tonnes x 10^3
print(c(a,b))
return(a*SSB/(1+b*SSB))
}
stored_rec_funs <- rep(list(rec_BH),5)
SSB <- rep(10e10,5)
rec_pars <- list(a=rep(1:5),b=seq(0.001,0.005,0.001))
然后
calc_recruits <- function(SSB, stored_rec_funs, rec_pars){
rec <- mapply(function(stored_rec_funs, SSB, ...){stored_rec_funs(SSB, ...)}, SSB=SSB, stored_rec_funs=stored_rec_funs,assign(names(rec_pars)[1],rec_pars[[1]]),assign(names(rec_pars)[2],rec_pars[[2]]))
return(rec)
}
calc_recruits(SSB, stored_rec_funs, rec_pars)
给出正确的答案。
但是,由于我实际上并不知道length(rec_pars)
,因此无法简单地写出:
assign(names(rec_pars)[1],rec_pars[[1]]),assign(names(rec_pars)[2],rec_pars[[2]])
是否可以针对未知长度的列表执行此操作?