[英]Rearranging column of a data frame in desired order in R
我有一個如下所示的數據框,並希望更改其列的順序。 我希望列的順序為:1、4、2、5、3、6。我該如何重新排序? 請注意,這是一個小例子,我有更多的列,我想像這樣對它們進行排序。 第一批的通用公式為 1+3x,第二批為 2+3x,最后一批為 3+3x,其中 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))
```
我們可以創建一個matrix
來重新排列列順序
medg[c(matrix(seq_along(medg), 2, byrow = TRUE))[seq_along(medg)]]
另外,如果我們想使用3 *
i1 <- rep(seq_len(ceiling(ncol(medg)/2)), each = 2) + 3 * (0:1)
medg[i1[seq_along(medg)]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.