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
tabulate() function in R Language is used to count the frequency of occurrence of a element in the vector.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With