簡體   English   中英

如何重新排列列,使名稱相似的列並排

[英]How to rearrange columns so that columns with similar names are side by side

我有一個如下所示的數據框:

live.1 死了.1 總計.1 live.2 死了2 總計 2 live.3 死了.3 總計 3
1 4 7 10 13 16 19 22 25
2 5 8 11 14 17 20 23 26
3 6 9 12 15 18 21 24 27

我想將名稱相似的列組合在一起,以便活動列在一起,並且死列和總數相同。 由於我希望列按自定義順序排列(即不按字母順序排列),因此我不能使用 order(names(df))。

我想重新排列列,使其看起來像這樣:

live.1 live.2 live.3 死了.1 死了2 死了.3 總計.1 總計 2 總計 3
1 10 19 4 13 22 7 16 25
2 11 20 5 14 23 8 17 26
3 12 21 6 15 24 9 18 27

如果可能,我還想添加分隔不同組的空列。 因此,一個空列將 live.3 和 dead.1 分開,另一個空列將 dead.3 和 total.1 分開。

這是重現示例的代碼:

df <- data.frame(c(1, 2, 3),
                 c(4, 5, 6),
                 c(7, 8, 9),
                 c(10, 11, 12),
                 c(13, 14, 15),
                 c(16, 17, 18),
                 c(19, 20, 21),
                 c(22, 23, 24),
                 c(25, 26, 27))
names(df) <- c("live.1", "dead.1", "total.1", "live.2", "dead.2", "total.2", "live.3", "dead.3", "total.3")

提前致謝!

一種(誠然有些難看)的選擇是預先確定順序。

cn <- as.character(t(outer(c("live.", "dead.", "total."), 1:3, paste0)))
df[cn]
#  live.1 live.2 live.3 dead.1 dead.2 dead.3 total.1 total.2 total.3
#1      1     10     19      4     13     22       7      16      25
#2      2     11     20      5     14     23       8      17      26
#3      3     12     21      6     15     24       9      18      27

我做了一個函數, live或 etc 旁邊的數字可能不在 1、2、3 中。

reorrder <- function(df, x){
  vec <- c()
  for (i in 1:length(x)){
    vec <- c(vec, which(grepl(x[i],names(df1))))
  }
  return(df[,vec])
}

如果你想要活的、死的和總的順序,

x <- c("live", "dead", "total")
reorrder(df1, x)

  live.1 live.2 live.3 dead.1 dead.2 dead.3 total.1 total.2 total.3
1      1     10     19      4     13     22       7      16      25
2      2     11     20      5     14     23       8      17      26
3      3     12     21      6     15     24       9      18      27

答案很簡單:

df[, sort(names(df))]
  dead.1 dead.2 dead.3 live.1 live.2 live.3 total.1 total.2 total.3
1      4     13     22      1     10     19       7      16      25
2      5     14     23      2     11     20       8      17      26
3      6     15     24      3     12     21       9      18      27

這里發生的事情是sort(names(df))只是按字母順序對列進行排序並將結果作為向量返回:

> sort(names(df))
[1] "dead.1"  "dead.2"  "dead.3"  "live.1"  "live.2"  "live.3"  "total.1"
[8] "total.2" "total.3"

然后,我們使用這樣一個事實,即您使用字符向量索引數據框的列(方括號中的第二項),這將返回與您提供的向量相同順序的列,例如

> df[, c('live.1', 'total.3')]
  live.1 total.3
1      1      25
2      2      26
3      3      27

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM