keep multiple rows based on the numbers of characters of a variable in r

Viewed 77

I have my dataframe:

df<-data.frame(ID=c("A","A","B","B","B","B","C","C","C"),
               VAL=c("L","LL","LL","LLL","LLLL","LLLLL","L","LL","LLL"))

df
  ID   VAL
1  A     L
2  A    LL
3  B    LL
4  B   LLL
5  B  LLLL
6  B LLLLL
7  C     L
8  C    LL
9  C   LLL

I would like to keep each of A, B, C with the most numbers of characters in VAL, like:

df
  ID   VAL
1  A    LL
2  B LLLLL
3  C   LLL

How to do that?

2 Answers
library(dplyr)
df %>%
  group_by(ID) %>%
  slice_max(nchar(VAL))

Another option could be filter:

df %>% 
  group_by(ID) %>% 
  filter(VAL == max(VAL))
Related