Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

How can I get the top n ranking of an array in R?

lets say I have

a <- c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100)

how can I get:

rank   number   times
1     100       4
2     2         3
3     67        2
4     23        1
4     89        1
like image 324
pedrosaurio Avatar asked Aug 14 '12 10:08

pedrosaurio


People also ask

How do I find the frequency of an element in a vector in R?

tabulate() function in R Language is used to count the frequency of occurrence of a element in the vector.

How do you find the highest frequency in R?

To find the most frequent factor value in an R data frame column, we can use names function with which. max function after creating the table for the particular column. This might be required while doing factorial analysis and we want to know which factor occurs the most.

How do you get top 5 values in R?

To get the top values in an R data frame, we can use the head function and if we want the values in decreasing order then sort function will be required. Therefore, we need to use the combination of head and sort function to find the top values in decreasing order.


1 Answers

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
like image 60
Roland Avatar answered Oct 08 '22 13:10

Roland