我想编写一个函数,该函数将创建并返回一组要在mySimulation
我创建的函数中使用的参数。到现在为止,我基本上一直在做,例如 mySimulation(parm1 = 3, parm2 = 4)
. 现在这是次优的,因为 (1) 在实际版本中,参数的数量变得难以处理,并且 (2) 我想跟踪产生我正在使用的不同模型的参数的不同组合。所以,我写了createParms
(下面显示的一个最低限度的版本)来做到这一点。不过,我的整个方法似乎很笨拙。由于所有统计学家都使用 R,我确信有一种更标准的方式来处理我的问题……对吗?
createParms <- function(model = "default", ...) {
# Returns a list `parms` of parameters which will then be used in
# mySimultation(parms)
#
# Args:
# model: ["default" | "mymodel"] character string representation of a model
# with known parameters
# ...: parameters of the existing `model` to overwrite.
# if nothing is supplied then the model parameters will be left as is.
# passed variables must be named.
# e.g., `parm1 = 10, parm2 = 20` is good. `10, 20` is bad.
#
# Returns:
# parms: a list of parameters to be used in mySimulation(parms)
#
parms.names <- c("parm1", "parm2")
parms <- vector(mode = "list", length = length(parms.names))
names(parms) <- parms.names
overwrite <- list(...)
overwrite.names <- names(overwrite)
if (model == "default") {
parms$parm1 <- 0
parms$parm2 <- 0
} else if (model == "mymodel") {
parms$parm1 <- 1
parms$parm2 <- 2
}
if (length(overwrite) != 0) {
parms[overwrite.names] <- overwrite
}
return(parms)
}