【问题标题】:How to order a data.frame based on row.names in another data frame?如何根据另一个数据框中的 row.names 对 data.frame 进行排序?
【发布时间】:2018-08-01 20:11:52
【问题描述】:

基本上,我有一个初始的data.frame,我使用参与者的名字为row.names。由于各种原因,我不得不堆叠然后合并长格式的数据,然后根据一个因子变量,我只选择了该数据的一部分。然后我将其汇总,因此我再次获得了广泛的数据,参与者为 row.names。但是,顺序不一样。因此,如果我想将 cbind 原始宽数据与新数据一起使用,它会弄乱我的数据,因为 row.names 的顺序不同。我尝试了sort()order()transform() 并阅读了几个问题,但我找不到解决方法。

DF1
>               V1           V2           V3
>     AAA        24           22           37
>     BBB        21           22           33
>     CCC        30           32           38
>     DDD        21           23           35

另一个数据框具有相同的dim(),但是row.names 的顺序不同。

DF2 row.names
>      BBB
>      CCC
>      AAA
>      DDD

我想根据rownames(DF2)DF1 进行排序,以便变量与行名保持一致,然后我可以cbind (D1, D2) 并且因为行名相等,所以同一个变量将属于同一个参与者。我可能把它复杂化了,对不起:)

基本上,我想根据DF2 中的行名对整个data.frame(DF1) 重新排序。

我知道这是一个蹩脚的问题,但我找不到有效的答案。

【问题讨论】:

    标签: r sorting dataframe


    【解决方案1】:

    这里有一个选项,使用内置的mtcars 数据框进行说明:

    # Create new sorted data frame. This is analogous to the second data frame
    # by which you want to sort the first one.
    mtcars.sorted = mtcars[order(rownames(mtcars)),]
    
    # Sort original data frame by the order of the new data frame
    mtcars[match(rownames(mtcars.sorted), rownames(mtcars)),]
    

    因此,在您的情况下,代码将是:

    DF1[match(rownames(DF2), rownames(DF1)), ]
    

    【讨论】:

    • 效果很好!多谢。我知道这是基础知识,但我找不到这个命令。
    【解决方案2】:

    您可以使用match

    > df <- data.frame(a=c("AAA","BBB","CCC"),b=1:3,c=6:8,d=9:11)
    > df
       a  b c  d
    1 AAA 1 6  9
    2 BBB 2 7 10
    3 CCC 3 8 11
    
    > df1 <- data.frame(a=c("CCC","AAA","BBB"))
    > df1
       a
    1 CCC
    2 AAA
    3 BBB
    
    > Final_df <- df[match(df1$a,df$a),]   ## Here it is
    > Final_df 
       a  b c  d
    3 CCC 3 8 11
    1 AAA 1 6  9
    2 BBB 2 7 10
    

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2020-08-04
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2021-04-05
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多