根据给定列中值的出现次数重新排列数据帧行

时间:2014-07-26 16:08:42

标签: r

示例第一:

a <- cbind(1:10, c("a","b","a","b","b","d","a","b", "d", "c"))
a
     [,1] [,2]
 [1,] "1"  "a" 
 [2,] "2"  "b" 
 [3,] "3"  "a" 
 [4,] "4"  "b" 
 [5,] "5"  "b" 
 [6,] "6"  "d" 
 [7,] "7"  "a" 
 [8,] "8"  "b" 
 [9,] "9"  "d" 
[10,] "10" "c" 

这就是我需要的:我想要重新调整此表的行,使这些行位于顶部,具有最频繁的第二列值。即我想要的结果是:

     [,1] [,2]
 [1,] "2"  "b" 
 [2,] "4"  "b" 
 [3,] "5"  "b" 
 [4,] "8"  "b"
 [5,] "1"  "a" 
 [6,] "3"  "a" 
 [7,] "7"  "a"
 [8,] "6"  "d" 
 [9,] "9"  "d" 
[10,] "10" "c"

我目前正在使用一个非常丑陋的for循环结构,它基本上运行一个已排序的count(a, 2)数据帧,然后重新组合一个新的数据帧。任何想法如何更整洁地做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用aveorder

使用ave计算每个“组”的长度,然后对该结果进行排序。如果你关心关系,rank也可能有用....

> a[order(ave(a[, 2], a[, 2], FUN = length), decreasing = TRUE), ]
      [,1] [,2]
 [1,] "2"  "b" 
 [2,] "4"  "b" 
 [3,] "5"  "b" 
 [4,] "8"  "b" 
 [5,] "1"  "a" 
 [6,] "3"  "a" 
 [7,] "7"  "a" 
 [8,] "6"  "d" 
 [9,] "9"  "d" 
[10,] "10" "c"

答案 1 :(得分:2)

标题是data.frame。使用data.tabledplyr

a1 <- as.data.frame(a)
library(data.table)
ans <- setDT(a1)[,N := .N, by = V2][order(-N)][, N := NULL]
#       V1 V2
#    1:  2  b
#    2:  4  b
#    3:  5  b
#    4:  8  b
#    5:  1  a
#    6:  3  a
#    7:  7  a
#    8:  6  d
#    9:  9  d
#   10: 10  c

或者

library(dplyr)
 a1%>% 
 group_by(V2) %>%
 mutate(L=n()) %>%
 arrange(desc(L)) %>%
 select(-L)