我对 R6 和面向对象编程都相当陌生,我真的不明白为什么我不能向方法调用的
weights
提供 subset
或 stats::lm()
。在下面的代码中,您可以看到,当使用这两个参数中的任何一个调用 stats::lm()
时,R 会抱怨找不到提供的变量。然而,提供的变量可以通过相同的方法打印,证明它们应该是可访问的。
gen_reg_data <- R6::R6Class(
classname = "regressionClass",
public = list(
initialize = function(data){
private$data <- data
},
lm = function(formula){
stats::lm(formula = formula, data = private$data)
},
weighted_lm = function(formula, weight_col){
weight_vec <- abs(private$data[, weight_col])
print(head(weight_vec))
tryCatch(
stats::lm(formula = formula,
weights = weight_vec,
data = private$data),
error = function(e) e
)
},
subset_lm = function(formula){
subset_vec <- private$data$X10 >= 0
print(head(subset_vec))
tryCatch(
stats::lm(formula = formula,
subset = subset_vec,
data = private$data),
error = function(e) e
)
}
),
private = list(
data = NULL
)
)
set.seed(1L)
raw_dat <- data.frame(matrix(rnorm(2600), nrow = 100))
tst_dat <- gen_reg_data$new(raw_dat)
# The following line print the results of lm
tst_dat$lm(formula = "X1 ~ X4")
# Following line prints the head of `weight_vec`, showing it's accessible but
# then an error message would pop up that weight_vec can't be found
tst_dat$weighted_lm(formula = "X1 ~ X4", weight_col = "X5")
# Following line does the same for `subset_vec`
tst_dat$subset_lm(formula = "X1 ~ X4")
我尝试添加那些
tryCatch
块和 print
行来检查所抱怨的变量是否可以通过方法访问。看起来是的,但是 stats::lm() 仍然找不到它们。
正如 @njp 所评论的,该问题是由 R 处理公式对象的方式引起的。最简单的解决方案似乎是将提供给
subset
或 weight
参数的变量作为 data
参数的列。下面的例子:
`
stats::lm(formula = formula,
weights = weight_vec,
data = cbind(private$data, weight_vec))
`