find kth most common elements in tidyverse in r

To find the Kth most common elements using tidyverse in R, we can use the combination of group_by(), count() and top_n() functions from the dplyr library.

Here is the code:

main.r
library(dplyr)

# create a sample data frame
df <- data.frame(
  x = c(1, 2, 2, 3, 3, 3, 4, 4, 5),
  y = c(6, 7, 7, 8, 8, 8, 9, 9, 10)
)

# group by the column and count the frequency
df_freq <- df %>%
  group_by(x) %>%
  count()

# select the Kth most common elements
k <- 2
df_topk <- df_freq %>%
  top_n(k, n)

# print the results
df_topk
342 chars
21 lines

In this code, we first create a sample data frame with two columns x and y. Then we group the data frame by the x column using group_by() and count the frequency using count(). Next, we select the Kth most common elements using top_n() where k is the desired number of elements. Finally, we print the results using df_topk.

gistlibby LogSnag