【问题标题】:Order columns in R based on numeric sequence根据数字序列对 R 中的列进行排序
【发布时间】:2020-07-17 16:58:52
【问题描述】:

我有专栏:

location, id_1, id_2, id_3, ..., id_20, name_1, name_2, name_3, ..., name_20

我想将它们重新排序,使其看起来像这样:

location, id_1, name_1, id_2, name_2, ..., id_20, name_20

select(location, ends_with("1"), ends_with("2"), etc. 有效,但对于 20 个变量是不可取的。

知道如何根据列名中的数字对变量重新排序吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以对列名上的子字符串进行排序

    library(dplyr)
    library(readr)
    df1 %>%
         select(location,   order(parse_number(names(.)[-1])) + 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 2022-12-18
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多