0

I'm quite new to R and working on conditions in R language. I have a dataframe looking like this :

ID   nb
11    1
11    2
11    3
24    1
24    2
32    1
41    1
41    2

And I want to subset rows where nb = max(nb) for each different ID, and so get this new dataframe :

ID   nb
11    3
24    2
32    1
41    2

If possible is there a way to do this without a loop ?

Thank you for your help

akben2
  • 39
  • 5

2 Answers2

1

Check out the tidyverse family of functions, which lets you do this very easily! They're very useful functions to be familiar with. (In particular, if you know the core dplyr functions, you can do most everything you'll need to do in R.)

data %>%
  group_by(ID) %>%
  filter(nb == max(nb)) %>%
  ungroup()
ila
  • 709
  • 4
  • 15
0

You can use aggregate with max and merge:

merge(x, aggregate(nb~ID, x, max))
#  ID nb
#1 11  3
#2 24  2
#3 32  1
#4 41  2
GKi
  • 37,245
  • 2
  • 26
  • 48