title: Stack columns in a dataframe together in the special case of columns="lags of variables" in R?
body: <p>(reproducible example given) How to stack columns in a dataframe together in the special case of columns="lags of variables"?</p>
  
  <pre><code>library(vars)
  decy &lt;- function(x, k=2) {format(round(x, k), nsmall=k)} # decimal number fixer
  set.seed(1)
  df &lt;- data.frame(replicate(4, rnorm(100)))
  coeflist &lt;- coef(VAR(df, p=6, type="none"))
  out &lt;- 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) &lt;- colnames(df)
  names(out) &lt;- c(paste(rep(colnames(df), 1), rep(1:6, each = 4),"l", sep=""))
  out
  </code></pre>
  
  <p>produces</p>
  
  <pre><code>    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
  </code></pre>
  
  <p>where X1, ..., X4 are variables, and X35l means X3's 5th lag. I want to stack lags of the variables together:</p>
  
  <pre><code>    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
  </code></pre>
  
  <p>There is a similar question in SOF (<a href="https://stackoverflow.com/questions/38471866/gather-multiple-groups-of-columns-in-r">Gather multiple groups of columns in R</a>), but I could not figure out how to finish from there.</p>