This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to select the variables with maximum values in each group with dplyr?

Hi there, I would like to extract taxa with 2 highest values, and extract those taxa from each group.

this is my data;

 data <- data.frame(group = rep(letters[1:3], each = 5),   
               value = rnorm(15),
               taxa = rep(make.unique(rep("taxa", 5)), 3))

Let's say 2 highest values correspond taxa are this two taxa.3 and taxa.

I would like to get this filtered data frame.

group    value        taxa

a        1.751479     taxa.3
a        1.75147938   taxa
b        1.47821190   taxa.3
b       -1.11304957   taxa
c       -0.72801722   taxa.3
c        0.15334196   taxa

Any help much appreciated!

r dplyr
library("dplyr")

data |>
  group_by(group) |>
  slice_max(value, n=2) |>
  ungroup()

thanks, for you reply, but it gives two maximum values for each group. In case of mine, I want to find two maximum values for whole data and then extract correspond taxa from each group.

1 answer

data |>
  group_by(taxa) |>
  slice_max(value, n=1) |>
  ungroup() |>
  slice_max(value, n=2) |>
  select(taxa) |>
  left_join(data)

Thanks a lot, it works. One more thing, in the case that I need five highest values as in the case of my real data, is there any shorter way to do this or I need to repeat slice_max until 5?

The first slice selects the largest value for each taxa, and the second slice selects the n=2 taxa with the largest values, so you can just change 2 to 5.

For more general advice biostars is not meant as a code writing service. It's recommended you go through each line of code provided to understand what it's doing. To learn more about tidyverse I recommend R for Data Science.

Log in to answer this question.