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
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
A dplyr solution to this could be:
library(dplyr)
df <- tibble(a = c(67, 2, 100, 2, 100, 23, 2, 100, 67, 89,100))
df %>%
count(a) %>%
mutate(rank = min_rank(-n)) %>%
arrange(desc(n)) %>%
rename(number = a, times = n)
#> # A tibble: 5 x 3
#> number times rank
#> <dbl> <int> <int>
#> 1 100 4 1
#> 2 2 3 2
#> 3 67 2 3
#> 4 23 1 4
#> 5 89 1 4
you can use df[df>0] <- 1, later rowSums(df), and finally with(df, df[order(-x, y, z), ] where -x is the column of frequency data and the others are I.D columns, and the suplementary information that you have.