Home > Back-end >  Rearranging column of a data frame in desired order in R
Rearranging column of a data frame in desired order in R

Time:11-16

I have a data frame as below and want to change the order of its columns. I want the columns in order as: 1, 4, 2, 5, 3, 6. How can I reorder this? Note that this is a small example and I have many more columns where I want to order them like this. The general formula would be 1 3x for the first batch, 2 3x for the second and 3 3x for the last one, where x=0,1,2,....

dput(medg)
structure(list(X1 = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 
3, 3, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 2, 3, 1, 
2, 3), X2 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2), 
    X3 = c(2, 3, 1, 2, 3, 1, 3, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 
    3, 2, 3, 1, 2, 3, 1, 3, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 3), 
    X4 = c(1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 1, 1, 
    1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2), 
    X5 = c(0, 0.2622587, 0.1040687, 0.1409907, 0, 0, 0.6184543, 
    0.9525439, 0.7830234, 0.3400703, 0.2622587, 0.6184543, 0.3765996, 
    0.907851, 0.5296791, 0.1040687, 0.9525439, 0.3765996, 0.5567241, 
    0.3325466, 0.1409907, 0.7830234, 0.907851, 0.5567241, 0.2221638, 
    0, 0.3400703, 0.5296791, 0.3325466, 0.2221638, 0, 0, 0, 0, 
    0, 0)), class = "data.frame", row.names = c(NA, -36L))
```

CodePudding user response:

We may create a matrix to rearrange the column order

medg[c(matrix(seq_along(medg), ncol = 3, byrow = TRUE))[seq_along(medg)]]

Also, if we want to use the 3 *

i1 <- rep(seq_len(ceiling(ncol(medg)/2)), each = 2)   3 * (0:1)
medg[i1[seq_along(medg)]]
  • Related