r functions calling lm with subsets

随声附和 提交于 2019-11-29 15:23:36

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  

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!