R calling lm with subsets

I was working on some code and I noticed something peculiar. When I run LM on a subset of some panel data, it works fine for me, 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 don't really understand what's going on here, but it breaks some other code I wrote, so I would like to know.

+3


source to share


2 answers


The problem is not subset related. I am getting the same error from your function when I go to subset = (state == 1)

. Arguments to your function are not passed or evaluated correctly.

I think you are 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  

      

+6


source


Most likely, you are facing problems with a non-standard rating (the function lm

uses a non-standard rating). Functions that use non-standard evaluations are convenient on the command line, but can cause problems when called from other functions.



Some additional readings on the topic include Standard Non-Standard Evaluation Rules and this chapter in Advanced R

+4


source







All Articles