【发布时间】:2017-10-25 02:07:03
【问题描述】:
当我通过lm() 函数在R 中计算线性模型时,可以将变量的字符向量传递给lm() 公式。 (例如,如here 或here 所述。)但是,如果我将相同的方法应用于sampleSelection 包的selection() 函数,则会出现以下错误:
detectModelType(选择,结果)中的错误: 参数“selection”必须是函数“selection()”中的公式
问题:有没有办法将变量的字符向量传递到selection() 公式中?
您可以在下面找到一个可重现的示例,该示例说明了问题:
# Example data
N <- 1000
y <- rnorm(N, 2000, 200)
y_prob <- c(rep(0, N / 2), rep(1, N / 2)) == 1
x1 <- y + rnorm(N, 0, 300)
x2 <- y + rnorm(N, 0, 300)
x3 <- y + rnorm(N, 0, 300)
x4 <- y + rnorm(N, 0, 300)
x5 <- y + rnorm(N, 0, 300)
y[1:(N / 2)] <- 0
data <- data.frame(y, x1, x2, x3, x4, x5, y_prob)
x_vars <- colnames(data)[colnames(data) %in% c("y", "y_prob") == FALSE]
# Estimate linear model via lm() --> works without any problems
lm(paste("y", "~", paste(x_vars, collapse = " + ")))
# Estimate Heckman model via selection()
library("sampleSelection")
# Passing of vector does not work
selection(paste("y_prob", "~", paste(x_vars[1:4], collapse = " + ")),
paste("y", "~", paste(x_vars[3:5], collapse = " + ")), data)
# Formula has to be written manually
selection(y_prob ~ x1 + x2 + x3 + x4, y ~ x3 + x4 + x5, data)
【问题讨论】:
-
你试过
as.formula吗? -
谢谢伊恩,成功了!