Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order unique values by frequency

Tags:

r

ranking

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

like image 277
user3358686 Avatar asked Dec 12 '22 06:12

user3358686


2 Answers

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"  
like image 131
Rich Scriven Avatar answered Jan 17 '23 14:01

Rich Scriven


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"
like image 27
Tyler Rinker Avatar answered Jan 17 '23 12:01

Tyler Rinker