在dplyr链中按升序排序列名。

4

I have this data.frame:

df <- structure(list(att_number = structure(1:3, .Label = c("0", "1", 
                                                      "2"), class = "factor"), `1` = structure(c(2L, 3L, 1L), .Label = c("1026891", 
                                                                                                                         "412419", "424869"), class = "factor"), `10` = structure(c(2L, 
                                                                                                                                                                                    1L, 3L), .Label = c("235067", "546686", "92324"), class = "factor"), 
               `2` = structure(c(3L, 1L, 2L), .Label = c("12729", "7569", 
                                                         "9149"), class = "factor")), .Names = c("att_number", "1", 
                                                                                                 "10", "2"), row.names = c(NA, -3L), class = "data.frame")    

看起来列名是数字。

att_number  1         10        2
         0  412419    546686    9149
         1  424869    235067    12729
         2  1026891   92324     7569

在dplyr链中,我想按升序排序列,就像这样:

att_number  1       2      10
         0  412419  9149   546686
         1  424869  12729  235067
         2  1026891 7569   7569

我尝试使用select_,但它并不按计划工作。有什么办法可以解决吗?这是我的努力:

names_order <- names(df)[-1] %>%
  as.numeric %>%
  .[order(.)] %>%
  as.character %>%
  c('att_number', .)

df %>%
  select_(.dots = names_order)

Error: Position must be between 0 and n

为什么不使用 .[ order(as.numeric(names(.))) ] 呢? - IRTFM
我想保留以字母开头的列。我可以通过添加另一个管道来实现:select(att_number, everything()),但如果可能的话,我想避免使用另一个管道... - maloneypatr
1个回答

3

更新:

对于较新版本的dplyr (>= 0.7.0):

library(tidyverse)

sort_names <- function(data) {
  name  <- names(data)
  chars <- keep(name, grepl, pattern = "[^0-9]") %>% sort()
  nums  <- discard(name, grepl, pattern = "[^0-9]") %>% 
    as.numeric() %>% 
    sort() %>% 
    sprintf("%s", .)

  select(data, !!!c(chars, nums))
}

sort_names(df)

Translated:

您需要使用反引号将数字列名括起来,以防止 select 试图将其解释为列位置:

library(tidyverse)

sort_names <- function(data) {
  name  <- names(data)
  chars <- keep(name, grepl, pattern = "[^0-9]") %>% sort()
  nums  <- discard(name, grepl, pattern = "[^0-9]") %>% 
             as.numeric() %>% 
             sort() %>% 
             sprintf("`%s`", .)

  select_(data, .dots = c(chars, nums))
}

sort_names(df)

请问您能否更新一下这个答案?它似乎已经失效了! - Anurag N. Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接