修改 lm 的包装函数中的权重参数

Modify weights argument in wrapper function for lm

我在 R 中有一个 lm 的包装函数。我想修改权重参数,如果被调用,然后再将它传递给 lm。有没有办法做到这一点?

例如,包装函数 myfunc 应将权重重置为 1,从而给出与未加权 lm 相同的系数。但是,这不会发生在这里:

#Load data
library(MASS)
data(Boston)

#Wrapper function for lm
myfunc <- function(formula, data, ...){
  if (!is.null(weights)){
    weights <- rep(1, nrow(data))
  }
  fit <- lm(formula, data, ...)
  return(fit)
}

#Build functions
myfunc('medv ~ .', Boston)
Call:
lm(formula = formula, data = data)

Coefficients:
(Intercept)         crim           zn        indus         chas          nox           rm          age  
  3.646e+01   -1.080e-01    4.642e-02    2.056e-02    2.687e+00   -1.777e+01    3.810e+00    6.922e-04  
        dis          rad          tax      ptratio        black        lstat  
 -1.476e+00    3.060e-01   -1.233e-02   -9.527e-01    9.312e-03   -5.248e-01  

myfunc('medv~.', Boston, weights=Boston$crim)
Call:
lm(formula = formula, data = data, weights = ..1)

Coefficients:
(Intercept)         crim           zn        indus         chas          nox           rm          age  
  83.809053    -0.117041     0.115602    -0.053765    10.245815   -38.463510    -0.580526     0.035360  
        dis          rad          tax      ptratio        black        lstat  
  -2.163867     0.265246    -0.008546    -1.311419     0.003468    -0.568235  

您实际上从未将权重向量传递给 lm()... 不只是传递函数中的任何变量。而且你不能真正修改 ... 中的变量。如果你想改变它们,你需要捕获它们。

myfunc <- function(formula, data, weights=NULL, ...){
  formula <- as.formula(formula)
  environment(formula) <- environment()
  if (!is.null(weights)){
    weights <- rep(1, nrow(data))
  }
  fit <- lm(formula, data, weights=weights, ...)
  return(fit)
}