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

时间:2016-10-27 20:17:34

标签: r dplyr chain

我有这个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

1 个答案:

答案 0 :(得分:2)

您需要在数字列名称周围返回刻度以停止选择尝试将它们解释为列位置:

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)
相关问题