【问题标题】:Sort Data Frame in a List in R在R中的列表中对数据框进行排序
【发布时间】:2021-02-10 06:32:40
【问题描述】:

假设我有名为 df1 到 df20 的数据框。这些数据框在一个列表中。

列表中数据名次的顺序是“df1”、“df10”、“df11”、“df12”, 如何使它成为“df1”、“df2”、“df3”、“df4”、?

【问题讨论】:

    标签: r


    【解决方案1】:

    创建一个名称向量并将它们子集化。如果列表名为dflist

    dflist <- dflist[paste0('df', 1:20)]
    

    也可以使用gtools::mixedsort

    dflist <- dflist[gtools::mixedsort(names(dflist))]
    

    【讨论】:

      【解决方案2】:

      stringr 函数str_sortstr_order 有一个参数numeric,当设置为TRUE 时按数字排序。这里有两种方法,假设data.frames列表命名为dflist

      dflist <- dflist[stringr::str_sort(names(dflist), numeric = TRUE)]
      
      i <- stringr::str_order(names(dflist), numeric = TRUE)
      dflist <- dflist[i]
      

      【讨论】:

        【解决方案3】:

        您可以使用sub 删除listnames 中的字符串df,使用as.integer 将结果转换为整数 并使用order 的输出以获得list 中的所需订单。

        dflist <- dflist[order(as.integer(sub("df", "", names(dflist))))]
        

        或者,您可以使用\\D 删除gsub 中的所有非数字。

        dflist <- dflist[order(as.integer(gsub("\\D", "", names(dflist))))]
        

        【讨论】:

          猜你喜欢
          • 2020-06-19
          • 2022-12-18
          • 2022-09-27
          • 1970-01-01
          • 2014-02-18
          • 1970-01-01
          • 2019-10-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多