问题
I'm trying to find the first most frequent, the second most frequent, ..., the last most frequent words/categories in the following text cat
.
library(stringr)
cat <- c("AA","AA","AA","Ee","Dd","Ee","Bb","Cc","Cc","Cc")
OUTPUT that I need:
most1 AAA Cc
most2 Ee
most3 Bb Dd
Can one help me in this regard? Tnx!
回答1:
You can use table
like:
sort(table(cat), TRUE)
#cat
#AA Cc Ee Bb Dd
# 3 3 2 1 1
And as a character vector:
x <- table(cat)
x <- rev(do.call(rbind, lapply(split(names(x), x), paste,collapse = " ")))
cbind(paste0("most", seq(x)), x)
# x
#[1,] "most1" "AA Cc"
#[2,] "most2" "Ee"
#[3,] "most3" "Bb Dd"
Variant:
x <- table(cat)
x <- do.call(rbind, rev(lapply(split(names(x), x), list)))
as.data.frame(cbind(paste0("most", seq(x)), x))
# V1 V2
#3 most1 AA, Cc
#2 most2 Ee
#1 most3 Bb, Dd
来源:https://stackoverflow.com/questions/62024263/how-to-find-the-first-most-frequent-second-most-frequent-last-frequent-in