0

(reproducible example given) How to stack columns in a dataframe together in the special case of columns="lags of variables"?

library(vars)
decy <- function(x, k=2) {format(round(x, k), nsmall=k)} # decimal number fixer
set.seed(1)
df <- data.frame(replicate(4, rnorm(100)))
coeflist <- coef(VAR(df, p=6, type="none"))
out <- as.data.frame(matrix(as.numeric(decy(matrix(c(coeflist[[1]][,1], coeflist[[2]][,1], coeflist[[3]][,1], coeflist[[4]][,1]), nrow=4, byrow=TRUE),3)), nrow=4))
rownames(out) <- colnames(df)
names(out) <- c(paste(rep(colnames(df), 1), rep(1:6, each = 4),"l", sep=""))
out

produces

    X11l   X21l   X31l  X41l   X12l   X22l   X32l   X42l   X13l   X23l   X33l
X1 0.029 -0.138 -0.160 0.110 -0.023  0.013 -0.080 -0.068 -0.090 -0.051  0.185
X2 0.088 -0.062 -0.117 0.017  0.065  0.009  0.165 -0.120 -0.053  0.056 -0.054
X3 0.069  0.212 -0.158 0.076 -0.135 -0.003  0.026 -0.127  0.159  0.201 -0.058
X4 0.001  0.078  0.064 0.119 -0.190 -0.013  0.128 -0.059  0.155  0.145 -0.184
     X43l   X14l   X24l  X34l   X44l   X15l   X25l   X35l   X45l   X16l   X26l
X1 -0.052 -0.100  0.035 0.007  0.050 -0.045  0.011  0.289  0.084 -0.071 -0.218
X2 -0.120  0.105  0.071 0.140  0.015  0.038  0.218  0.081 -0.036 -0.141  0.069
X3  0.088  0.180  0.040 0.007  0.164  0.122 -0.025 -0.111 -0.030  0.028 -0.271
X4  0.064 -0.072 -0.046 0.059 -0.089  0.006  0.001 -0.102 -0.020 -0.109  0.079
     X36l   X46l
X1  0.029 -0.006
X2  0.141  0.012
X3 -0.092 -0.075
X4 -0.039 -0.023

where X1, ..., X4 are variables, and X35l means X3's 5th lag. I want to stack lags of the variables together:

    X11l X12l ...X16l X21l X22l ...X26l...  X41l X42l ... X46l
X1  0.029 -0.023
X2  0.088 0.065
X3  0.069 -0.135
X4  0.001 -0.190

There is a similar question in SOF (Gather multiple groups of columns in R), but I could not figure out how to finish from there.

Community
  • 1
  • 1
Erdogan CEVHER
  • 1,586
  • 15
  • 33

1 Answers1

0

From bad solutions:
1.

out[,c(1,5,9,13,17,21, 2,6,10,14,18,22, 3,7,11,15,19,23, 4,8,12,16,20,24)]

2.

out[,c(seq(1,21,by=4), seq(2,22,by=4), seq(3,23,by=4), seq(4,24,by=4))]

I eventually obtained an acceptable (to me) solution:

3.

out[,unlist(lapply(1:4, function(x){seq(x, 24, by = 4)}))] 
Erdogan CEVHER
  • 1,586
  • 15
  • 33