将权重传递给函数中的 lm 和其他函数

Passing weights to lm and others within a function

我有如下数据:

library(estimatr)
DF <- structure(list(country = c("C", "C", "C", "C", "J", "J", "B", 
"B", "F", "F"), year = c(2005, 2010, 2010, 2005, 2005, 2010, 
2010, 2005, 2010, 2005), sales= c(15.48, 12.39, 3.72, 23.61, 
4, 31.87, 25.33, 7.64, 0.26, 2.9), industry = c("D", "D", "E", 
"E", "F", "F", "F", "F", "D", "D"), urbanisation = c("B", "B", 
"A", "A", "B", "B", "A", "A", "C", "C"), size = c(1, 1, 5, 5, 
5, 5, 1, 1, 1, 1), wt = c(14L, 14L, 14L, 14L, 19L, 19L, 
30L, 30L, 20L, 20L), taxrate = c(12L, 14L, 14L, 12L, 21L, 18L, 
30L, 30L, 20L, 20L), vote = c(0, 0, 0, 0, 1, 1, 1, 0, 1, 1), 
    votewon = c(0, 0, 0, 0, 1, 0, 1, 0, 1, 1)), row.names = c(NA, 
10L), class = "data.frame")

我在一个函数中调用 lmlm_robust。该示例应该是我正在使用的函数的简化版本,不知何故,lmweights=weights 作为参数,而 lm_robust 在做同样的事情时失败了。现在,当我尝试重新创建错误时,它们都失败了..

我应该如何将 weights 参数传递给此函数?

lm_coll <- function (data=data, weights=weights) {

    a <- lm(sales~size+taxrate+industry, weights=weights, data=data)
    summary(a)
    b <- lm_robust(sales~size+taxrate+industry, weights=weights, data=data)
    summary(b)
}

lm_coll(DF, weights=wt)

据我所知,您希望将权重列名称作为字符串传递,而不是使用 $ 引用它(根据我上面的评论)。实现此目的的一个简单方法是:

lm_coll <- function (data, weight) {
    weights = data[,weight]

    a <- lm(sales~size+taxrate+industry, weights=weights, data=data)
    print(summary(a))
    b <- lm_robust(sales~size+taxrate+industry, weights=weights, data=data)
    print(summary(b))
}

lm_coll(data=DF, weight='wt')

您的版本失败的原因是 R 试图从 lm_coll 中的本地环境中找到一个名为 wt 的对象。显然这不存在,因为环境只包含 DF 和一个名为 wt 的列。我的函数版本在环境中创建了一个名为 weights 的新对象。