Question

I am running multiple univariate regressions, like in this reproducible example:

require(dynlm)
data(USeconomic)
US<-USeconomic
vars<-colnames(US)[-2]
a<-lapply(colnames(US),function(x) dynlm(log(GNP)~get(x),data=US))

a contains a list of 3 univariate regressions. Assume now I´d like to run the same regressions with 3 lags: l<-c(0,1,4) where 0 is of course the case I already got. Is there a way to use the vector ldirectly, like

# this did not work for me, I obtain multivariate regressions including all lags at once
lapply(colnames(US),function(x) dynlm(log(GNP)~L(get(x),l),data=US),l=l)

After this did not work I tried another approach and added to following vector:

lagged_vars <- paste("L(",rep(vars,each=3),",",l,")",sep="")

to get:

[1] "L(log(M1),0)" "L(log(M1),1)" "L(log(M1),4)" "L(rs,0)"      "L(rs,1)"     
[6] "L(rs,4)"      "L(rl,0)"      "L(rl,1)"      "L(rl,4)"

Unfortunately, I can't run it with the new character vector, get() does not help. I can't understand why cause it works with vars but not lagged_vars which are both character vectors.

Note, that the L() syntax comes from the dynlm package. Side question: If I just print a the coefficients from the regression result remain labelled get(x) – how can I change that?

An i,j loop could be possible solution but I´d rather use lapply or something out of this family...

EDIT: as.formula does not work together with L() from dynlm. I get the this error message:

Error in merge.zoo(log(GNP), L(log(M1), 0), retclass = "list", all = FALSE) : could not find function "L"

EDIT: found an interesting post bei Achim Zeileis referring to this problem.

Was it helpful?

Solution

Here is an approach using plyr

library(plyr); library(dynlm); library(tseries)

# FUNCTION TO RUN A SINGLE REGRESSION
foo = function(x, l) dynlm(log(GNP) ~ L(get(as.character(x)), l), data = US)

# CREATE PARAMETER GRID
params = expand.grid(x = colnames(US)[-2], l = c(0, 1, 4))

# RUN REGRESSIONS
regressions = mlply(params, foo)

Each element of this list contains details on a single regression from which you can extract your desired output

OTHER TIPS

To construct R formula, you must paste it all together, not just the predictor side of it. So you need something like:

formula <- as.formula(
    paste("log(GNP)~",
        paste("L(",rep(vars,each=3),",",l,")",sep=""),
        sep = ""
    )
)

and then run

dynlm(formula, data = ...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top