I have a data.frame that I want to summarise to get the highest (5 values) and the lowest (5 values) for each column. I used iris for a reproducible example.
The highest 5 values for all variables in iris can be obtained using
df_h <- iris %>%
dplyr::select(Species, everything()) %>%
tidyr::gather("id", "value", 2:5) %>%
dplyr::arrange(Species, id, desc(value)) %>%
dplyr::group_by(Species, id ) %>%
top_n(n = 5) %>%
dplyr::mutate(category = "high")
for the lowest 5 values, I used the same except top_n(n = -5).
df_l <- iris %>%
dplyr::select(Species, everything()) %>%
tidyr::gather("id", "value", 2:5) %>%
dplyr::arrange(Species, id, desc(value)) %>%
dplyr::group_by(Species, id ) %>%
top_n(n = -5) %>%
dplyr::mutate(category = "low")
Then, I joined the two data.frames together df_h (the highest 5 values) and df_l (the lowest 5 values).
df_fin <- df_h %>% bind_rows(., df_l)
I'm looking for an efficient/shorter way to get the same result without having to create two data.frames and join them. Any suggestions will be appreciated.