r函数用子集调用lm [英] r functions calling lm with subsets

查看:397
本文介绍了r函数用子集调用lm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些代码,并且发现了一些奇怪的东西。
当我在某些面板数据的子集上运行LM时,我的工作正常,如下所示:

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('plm')
data(Cigar)
lm(log(price) ~ log(pop) + log(ndi), data=Cigar, subset=Cigar$state==1)

Call:
lm(formula = log(price) ~ log(pop) + log(ndi), data = Cigar, 
subset = Cigar$state == 1)


Coefficients:
(Intercept)     log(pop)     log(ndi)  
  -26.4919       3.2749       0.4265  

但是当我试图在一个函数中包装这个时,我得到:

but when I try to wrap this in a function I get:

myfunction <- function(formula, data, subset){
  return(lm(formula, data, subset))
}

myfunction(formula = log(price) ~ log(pop) + log(ndi), data = Cigar, subset = Cigar$state==1)

Error in xj[i] : invalid subscript type 'closure'

我真的不明白这里发生了什么,但它破坏了我写的其他代码,所以我想知道。

I really don't understand what's going on here, but it's breaking some other code I've written so I would like to know.

推荐答案

这个问题似乎与子集无关。当我更改为 subset =(state == 1)时,我从您的函数中得到相同的错误。您的函数的参数不被正确传递和评估。

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.

我认为您最好使用 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  

这篇关于r函数用子集调用lm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆