I'm trying to get the top 10 lowest 'key_val' for each group = 'loc'
Table df2:
Trends | loc | key_val |
---|---|---|
trend1 | Nigeria | 1 |
trend1 | Nigeria | 1 |
trend2 | Nigeria | 2 |
trend2 | Nigeria | 2 |
trend3 | France | 3 |
trend4 | France | 4 |
trend5 | France | 5 |
trend6 | France | 6 |
trend6 | France | 6 |
The table is not exhaustive but an example
I tried the following code:
data_new3 <- df2[order(df2$key_val, decreasing = FALSE), ]
data_new3 <- data.table(data_new3, key = "loc")
data_new3 <- data_new3[ , tail(.SD, 10), by = loc]
data_new3
The result does not take into account the top 10 lowest values (key_val), but only the first or second.... I don't know how to solve this problem, can anyone help me?
We may do
library(dplyr)# version >= 1.1.0
df1 %>%
slice_min(key_val, n = 10, by = loc)