问题
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