Reputation: 151
I have a grouped data frame and I wish to keep for each group (name) the rows in a given range .For ex, between 2nd and 3rd position.
df <- data.frame(name = c("a", "a", "a", "b", "b", "c", "c", "c", "c"), x = 1:9)
df
name x
1 a 1
2 a 2
3 a 3
4 b 4
5 b 5
6 c 6
7 c 7
8 c 8
Here I want an output like this
name x
1 a 2
2 a 3
3 b 5
4 c 7
5 c 8
Thank you,
Upvotes: 0
Views: 95
Reputation: 21400
First, group_by
name
, then slice
from index 2:3
:
library(dplyr)
df %>%
group_by(name) %>%
slice(2:3)
# A tibble: 5 x 2
# Groups: name [3]
name x
<chr> <int>
1 a 2
2 a 3
3 b 5
4 c 7
5 c 8
Upvotes: 1