8
df <- data.frame(id=c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3), 
             x=c(1,2,3,3,5,1,4,3,1,2,8,9,3,1,0))

For each group, if I want to filter the first row

 df %>%
 group_by(id) %>%
filter(row_number()==1)

What do I do if I have to filter the most middle row?

89_Simple
  • 3,393
  • 3
  • 39
  • 94

2 Answers2

9

n()/2 halves the nrow of the group, ceiling rounds up decimals for odd values.

df %>%
  group_by(id) %>%
  filter(row_number()==ceiling(n()/2))

# A tibble: 3 x 2
# Groups:   id [3]
     id     x
  <dbl> <dbl>
1     1     3
2     2     3
3     3     3
LAP
  • 6,605
  • 2
  • 15
  • 28
4

You can also use slice rather than row_number() and do use n() to capture the length of each group. Divide that by 2 to get the middle value of each group.

library(dplyr)

df %>% 
 group_by(id) %>% 
 slice(ceiling(n()/2))
Sotos
  • 51,121
  • 6
  • 32
  • 66