r functions calling lm with subsets

后端 未结 2 562
不思量自难忘°
不思量自难忘° 2020-12-21 08:18

I was working on some code and I noticed something peculiar. When I run LM on a subset of some panel data I have it works fine, something like this:

library(         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 08:54

    The problem doesn't seem to be with the subset. I get the same error from your function when I change to subset = (state == 1). The arguments to your function aren't being passed and evaluated correctly.

    I think you'd be better off using do.call

    myfunction <- function(formula, data, subset) {
        do.call("lm", as.list(match.call()[-1]))
    }
    
    myfunction(log(price) ~ log(pop) + log(ndi), Cigar, state == 1)    
    # Call:
    # lm(formula = log(price) ~ log(pop) + log(ndi), data = Cigar, 
    #     subset = state == 1)
    #
    # Coefficients:
    # (Intercept)     log(pop)     log(ndi)  
    #    -26.4919       3.2749       0.4265  
    

提交回复
热议问题