r functions calling lm with subsets

后端 未结 2 557
不思量自难忘°
不思量自难忘° 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  
    
    0 讨论(0)
  • 2020-12-21 09:00

    You are most likely running into problems with Non-Standard evaluation (the lm function uses non-standard evaluation). Functions that use non-standard evaluation are convenient at the command line, but can cause problems when called from within other functions.

    Some additional reading on the topic include Standard Nonstandard Evaluation Rules and this chapter in Advanced R

    0 讨论(0)
提交回复
热议问题