Passing weights to lm and others within a function

Viewed 56

I have data as follows:

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")

I am calling lm and lm_robust from within a function. The example was supposed to be a simplified version of a function I am using, where somehow, lm takes weights=weights as an argument and lm_robust fails when doing the same thing. Now when I tried to recreate the error, they both fail..

How am I supposed to pass the weights argument to this function?

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)
1 Answers

As far as I can tell, you want pass the weight column name as a string instead of referencing it with a $ (as per my comment above). A simple way to accomplish this is to do:

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')

The reason why your version fails, is that R is trying to find an object called wt from the local environment within lm_coll. Obviously that does not exist, because the environment only contains DF with a column called wt. My version of the function creates a new object called weights into the environment.

Related