8

如何获得R中数组的前n个排名?

可以说我有

a <- c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100)

我怎样才能得到:

rank   number   times
1     100       4
2     2         3
3     67        2
4     23        1
4     89        1
4

6 回答 6

10
tab <- table(a<-c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100))
df <- as.data.frame(tab)
names(df) <- c("number","times")
df$rank <- rank(-df$times,ties.method="min")
df <- df[order(df$rank,decreasing = F),]
df
  number times rank
5    100     4    1
1      2     3    2
3     67     2    3
2     23     1    4
4     89     1    4
于 2012-08-14T10:24:27.730 回答
7

table与 一起使用sort

sort(table(a), decreasing=TRUE)
a
100   2  67  23  89 
  4   3   2   1   1 

如果要将结果转换为数据框,只需将所有这些包装成data.frame()

data.frame(count=sort(table(a), decreasing=TRUE))
    count
100     4
2       3
67      2
23      1
89      1
于 2012-08-14T10:25:03.130 回答
3

你可以尝试这样的事情:

a <- c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100)
DF <- as.data.frame(table(a))

DF[order(DF[,2], decreasing = TRUE), ]
    a Freq
5 100    4
1   2    3
3  67    2
2  23    1
4  89    1
于 2012-08-14T10:21:24.207 回答
1

或者count从 plyr 包中使用:

require(plyr)
df = count(a)
df[order(df[["freq"]], decreasing = TRUE),] 
    x freq
5 100    4
1   2    3
3  67    2
2  23    1
4  89    1
于 2012-08-14T10:27:46.417 回答
1

对此的dplyr解决方案可能是:

library(dplyr)
df <- tibble(a = c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100))
df %>% 
  count(a) %>% 
  mutate(rank = min_rank(-n)) %>%
  arrange(desc(n)) %>% 
  rename(number = a, times = n)
#> # A tibble: 5 x 3
#>   number times  rank
#>    <dbl> <int> <int>
#> 1    100     4     1
#> 2      2     3     2
#> 3     67     2     3
#> 4     23     1     4
#> 5     89     1     4
于 2017-10-05T03:36:49.377 回答
0

您可以使用df[df>0] <- 1,稍后rowSums(df),最后频率数据列with(df, df[order(-x, y, z), ]在哪里-x,其他是 ID 列,以及您拥有的补充信息。

于 2017-10-05T03:05:37.337 回答