I have a data frame with four columns, and want transform it to a data frame with 2 columns, but sequence matters (so stack or merge without additional sorting is not an option)
X1 Y1 X2 Y2
1 2 3 4
5 6 7 8
To
X1 Y1
1 2
3 4
5 6
7 8
My ugly version:
nrow = 4
# Test data set
d = setNames(data.frame(matrix(sample(1:(nrow*4)), nrow=nrow)),
c("X1","Y1","X2","Y2"))d
# Create empty data frame
d1 = data.frame(matrix(rep(NA, nrow*2*2), nrow = nrow*2))
# Elements 1, 3, 5...
d1[seq(1, nrow*2, by = 2),] = d[,1:2]
# Elements 2, 4, 6...
d1[seq(2, nrow*2, by = 2),] = d[,3:4]
Not necessary base R.
Added later: I just found:
data.frame(matrix(as.vector(t(as.matrix(d))), nrow = 2*nrow, byrow = TRUE))
but looks like @akrun has a slightly simpler version of it
The alternative solution in the post mentioned by @alistaire, for example using reshape
, are definitively not more elegant than my orginal version.