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 l
directly, 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.
To construct R formula, you must paste it all together, not just the predictor side of it. So you need something like:
and then run
Here is an approach using
plyr
Each element of this list contains details on a single regression from which you can extract your desired output