Order unique values by frequency

天大地大妈咪最大 提交于 2019-12-02 01:02:00

问题


What function do I need to use to rank first four most popular words in list in R program?

For example,

c("apple", "banana", "apple", "banana", "banana", 
  "desk", "pen", "pen", "pen", "pen")

to make it like

"pen"
"banana"
"apple"
"desk"

Thank you


回答1:


You can sort the tabled values in decreasing order and then take the names to get the output you're looking for. Try this:

> x <- c("apple", "banana", "apple", "banana", "banana", 
         "desk", "pen", "pen", "pen", "pen")
> names(sort(table(x), decreasing = TRUE))
## [1] "pen"    "banana" "apple"  "desk"  



回答2:


table is intuitive for base R. Here's a qdap approach:

library(qdap)
freq_terms(dat, 4)

##   WORD   FREQ
## 1 pen       4
## 2 banana    3
## 3 apple     2
## 4 desk      1

Or...

freq_terms(dat, 4)[, 1]
## [1] "pen"    "banana" "apple"  "desk"



回答3:


An efficient way to do this would be:

k <- {tmp <- table(x); names(tmp)[order(tmp, decreasing = TRUE)]}
k
[1] "pen"    "banana" "apple"  "desk" 


来源:https://stackoverflow.com/questions/23233833/order-unique-values-by-frequency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!