-1

How can I create a subset by the highest value of a certain variable in a data frame?

I have the following dataframe, from which I want to extract the highest value of V1 by name:

   name V1 V2
1 name1  1  f
2 name1  2  b
3 name1  5  c
4 name2  3  f
5 name2  8  g
6 name2  2  m

The subset should look like this

   name V1 V2
3 name1  5  c
5 name2  8  g
xyz
  • 134
  • 1
  • 12

1 Answers1

-1

We can use dplyr. After grouping by 'name' slice the row which have the maximum value for 'V1'

library(dplyr)
df1 %>% 
    group_by(name) %>% 
    slice(which.max(V1))
#    name    V1    V2
#   <chr> <int> <chr>
#1 name1     5     c
#2 name2     8     g
akrun
  • 874,273
  • 37
  • 540
  • 662