对于R中的用户定义函数,Do.call返回缺少的参数

对于R中的用户定义函数,Do.call返回缺少的参数,r,R,我试图在另一个函数(称为B)中使用一个函数(称为a)(我定义了这两个函数)。为此,我在B函数的开头定义了A的一些参数,然后使用do.call调用了A。然而,函数A不能识别这些参数,即使它们刚刚被定义。发生什么事了 上下文:我正在尝试运行一个简单系统的模拟。为此,我将问题分解为多个子函数:一个(genpar)生成随机参数供模拟使用,另一个(indeffbasic)从参数值映射到变量值。然后,我将这两个函数合并到一个名为indeff的新函数中。就是在这最后一步发生了错误。我到处找了,但找不到任何解决

我试图在另一个函数(称为B)中使用一个函数(称为a)(我定义了这两个函数)。为此,我在B函数的开头定义了A的一些参数,然后使用do.call调用了A。然而,函数A不能识别这些参数,即使它们刚刚被定义。发生什么事了

上下文:我正在尝试运行一个简单系统的模拟。为此,我将问题分解为多个子函数:一个(genpar)生成随机参数供模拟使用,另一个(indeffbasic)从参数值映射到变量值。然后,我将这两个函数合并到一个名为indeff的新函数中。就是在这最后一步发生了错误。我到处找了,但找不到任何解决办法。如果答案显而易见,请原谅我。见下面的代码:

#First we set up the data structure. 
#In this simple model we have N variables, and each variable has a value at each time period. 
#There are T time periods.
N <- 2
T <- 20
variables <- data.frame(matrix(0,T,N))
#I assign names to the variables, and check that I've given the right number of names
Names <- c("Movement", "AIpapers")
if(length(Names)==N){names(variables) <- Names} else {print("Error")}

#Now I assign the basic function that, given parameter values, runs a simulation over T time periods.
indeffbasic <- function(a0=5000, b0=100, a1, b1){
    for (i in 1:T) {
        variables[i, "Movement"] <- (if(i-1>0){a1* variables[i-1, "Movement"]}else{a0})
        variables[i, "AIpapers"] <- (if(i-1>0){variables[i-1, "AIpapers"]}else{b0}) + (if(i-3>0){b1*variables[i-3, "Movement"]}else {0})
    }
    return(variables)
}

#This function works:
indeffbasic(a1=10, b1=2)

#Since I want a1 and b1 to be randomly generated each time, 
#I define a function that randomly generates these values and returns them
genpar <- function () {
    a1 <- rnorm(1, 1.1, 0.02)
    b1 <- rnorm(1)
    parameters <- c(a1, b1)
    return(parameters)
}

#This function also seems to work
genpar()

#Now I define a function that randomly generates a1 and b1
#and then passes them to the indeffbasic function I defined above
#so each time I call this is like a run of the simulation.
indeff <- function(a0=5000, b0=100) {
    parameters <- as.list(c(a0, b0, genpar()))
    names(parameters) <- c("a0", "b0", "a1", "b1")
    return(do.call(indeffbasic(), parameters))
}

#But this doesn't work: it returns "Error: argument "a1" is missing, with no default"
indeff()
#首先我们设置数据结构。
#在这个简单的模型中,我们有N个变量,每个变量在每个时间段都有一个值。
#没有时间段。
在你的队伍中

return(do.call(indeffbasic(), parameters))
do.call
的第一个参数应该是函数(或函数名),而不是函数调用。因此,将其替换为

return(do.call(indeffbasic, parameters))
或者只是

do.call(indeffbasic, parameters)

因为函数中最后一个表达式的值是返回值。

genpar
返回单个向量(因为
c
)。您可以让它返回一个命名列表(通过将
c(a1,b1)
替换为
list(“'a1=a1,“b1”=b1)
),然后提取a1和b1。谢谢@lmo,您是对的。