R:关于函数何时理解其参数的一些提示?

R: Some hints on when a function understands its argument?

我正在尝试编写一个可以应用于字符串向量或列表的函数,而不是编写一个循环。我的目标是 运行 对不同的内生变量进行回归并保存结果表。既然有经验的 R 用户告诉我们应该学习应用函数,我想试一试。这是我的尝试:

破例:

library(ExtremeBounds)
Data <- data.frame(var1=rbinom(30,1,0.2),var2=rbinom(30,1,0.2),var3=rnorm(30),var4=rnorm(30),var5=rnorm(30),var6=rnorm(30))

spec1 <- list(y=c("var1"),freevars=("var3"),doubtvars=c("var4","var5"))
spec2 <- list(y=c("var2"),freevars=("var4"),doubtvars=c("var3","var5","var6"))
specs <- c("spec1","spec2")

myfunction <- function(x){
eba <- eba(data=Data, y=x$y, 
       free=x$freevars, 
       doubtful=x$doubtvars, 
       reg.fun=glm, k=1, vif=7, draws=50, se.fun = se.robust, weights = "lri", family = binomial(logit))

output <- eba$bounds
output <- output[,-(3:7)]
}

lapply(specs,myfunction)

这给了我一个错误,让我猜测 R 不理解什么时候 x 应该是 "spec1""spec2"。另外,我不太明白 lapply 会在这里收集什么。你能给我一些最好的 practice/hints 如何将这些东西传达给 R 吗?

错误:Error in x$y : $ operator is invalid for atomic vectors

工作示例:

这是 spec1 的一个工作示例,它没有使用 apply 来展示我正在尝试做的事情。我想通过 7 个规范循环此示例,但我正试图摆脱循环。输出不必保存为 csv,所有输出的列表或任何其他集合都很棒!

eba <- eba(data=Data, y=spec1$y, 
       free=spec1$freevars, 
       doubtful=spec1$doubtvars, 
       reg.fun=glm, k=1, vif=7, draws=50, se.fun = se.robust, weights = "lri", family = binomial(logit))
output <- eba$bounds
output <- output[,-(3:7)]
write.csv(output, "./Results/eba_pmr.csv")

根据@user20650的评论,解决方法很简单:

在 lapply 命令中,使用 lapply(mget(specs),myfunction) 获取规范列表元素的名称,而不是列表本身。

或者,可以将 specs 定义为一个列表:specs <- list(spec1,spec2) 但这样做的缺点是 lapply 命令将 return 一个包含不同规范的列表编号。第一个版本保留了规范的名称(spec1spec2),这使得使用结果列表更容易。