簡體   English   中英

如何從R中的向量中獲取前n個元素(就頻率而言)?

[英]How to get the top n elements (in terms of frequency) from a vector in R?

如何在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
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

使用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

你可以嘗試這樣的事情:

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

或者使用plyr包中的count

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

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

您可以使用df[df>0] <- 1 ,稍后使用rowSums(df) ,最后with(df, df[order(-x, y, z), ] ,其中-x是頻率數據列和其他是ID列,以及您擁有的完整信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM