1

I wrote a small function to run multiple univariate regressions with different lags:

f <- function(x,l) {
lm.obj <- dynlm(GNP~L(get(as.character(x)),l),
              data=longley)
names(lm.obj$coefficients)[2] <- paste(x,l,sep=".")
return(lm.obj)
}

this works quite well with mlply after creating a frame of possible lag - variable combinations using expand.grid. A reproducible example using the longley dataset from the datasets package looks like this:

data(longley)
require(plyr)
vars <- expand.grid(x=names(longley)[-c(1:3)],l=1:3)

regressionList <- mlply(vars,f, .progress= "text")
summaries <- lapply(regressionList,summary)

This works quite well. However now I try to do the same thing using gls.

require(nlme)

f.gls <- function(x,l) {
gls.obj <- gls(GNP~lag(get(as.character(x)),-l),
              data=longley)
names(gls.obj$coefficients)[2] <- paste(x,l,sep=".")
return(gls.obj)
}

But all I get is this error:

Error in eval(expr, envir, enclos) : object 'x' not found

I tried to use debug() but everything on the inside seems the same. I als tried to call the function outside mlply but it did not work. Also tried with out lags. It's just that x can"t be found.

Matt Bannert
  • 27,631
  • 38
  • 141
  • 207
  • 1
    you probably want something like `f <- as.formula(paste("depvar~lag(",x,",-1)")); gls(f,...)` – Ben Bolker Apr 09 '12 at 20:16
  • Thanks for the suggestion. I was so mad, it did not work that I forgot about as.formula. Thanks for the reminder! Do you have any idea why it works we dynlm but not with gls? – Matt Bannert Apr 09 '12 at 21:20
  • As I'm sure you know, you can always consult the source and look for key differences. – Chase Apr 09 '12 at 22:10
  • @Chase, good point. I was just asking whether someone had already wondered and done that for me. since debug() did not really help me... I am not too optimistic about the source, but I guess I should give it a try. – Matt Bannert Apr 09 '12 at 22:24
  • evaluating the variables within formulas is tricky and fragile. It's mildly, but not very, surprising that what you want works in `dynlm` and not in `gls` ... – Ben Bolker Apr 09 '12 at 22:36
  • actually not quite reproducible, I think -- have you tried it? I had trouble with `mydata`, then with `depvar` ... – Ben Bolker Apr 09 '12 at 22:40
  • oups.sorry! edited that. Thanks for the note. – Matt Bannert Apr 09 '12 at 22:54

0 Answers0