To simplify (and to check my understanding), your problem boils down to how to reshape a single column of a data.frame
in such a way that this column is split at every 10th element.
There is a function in base R that does this, called unstack
. You can use this on your problem as follows.
First set up some dummy data:
df <- data.frame(
A=1:50,
B=101:150
)
Now, to use unstack
we need to create a temporary data.frame
that contains our data to unstack as well as an indicator on how to unstack. The indicator in your case is a repeating vector of 1:10
, created using rep
:
tmp <- data.frame(
X=df$B,
ind=rep(1:10, nrow(df)/10)
)
Then use some unstack
magic:
unstack(tmp, X~ind)
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 101 102 103 104 105 106 107 108 109 110
2 111 112 113 114 115 116 117 118 119 120
3 121 122 123 124 125 126 127 128 129 130
4 131 132 133 134 135 136 137 138 139 140
5 141 142 143 144 145 146 147 148 149 150
Combine it with your the subset of your first column in the original df
:
rbind(A=df$A[1:10], unstack(tmp, X~ind))
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
A 1 2 3 4 5 6 7 8 9 10
2 101 102 103 104 105 106 107 108 109 110
3 111 112 113 114 115 116 117 118 119 120
4 121 122 123 124 125 126 127 128 129 130
5 131 132 133 134 135 136 137 138 139 140
6 141 142 143 144 145 146 147 148 149 150