Reputation: 697
Let's say i have the mtcars
dataframe and I group the observations by the cyl
. Now I want to select all the obsevations which fall in the first group. I'm not really sure how I can do that. I tried something like:
mtcars %>%
group_by(cyl) %>%
slice_head(n=1)
But I think this gives me the first observation of each group. I instead want all the observations from the first group.
Upvotes: 0
Views: 178
Reputation: 389055
To get all the rows in the first group you can use cur_group_id() == 1
.
library(dplyr)
mtcars %>% group_by(cyl) %>% filter(cur_group_id() == 1)
# mpg cyl disp hp drat wt qsec vs am gear carb
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
# 2 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
# 3 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2
# 4 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
# 5 30.4 4 75.7 52 4.93 1.62 18.5 1 1 4 2
# 6 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
# 7 21.5 4 120. 97 3.7 2.46 20.0 1 0 3 1
# 8 27.3 4 79 66 4.08 1.94 18.9 1 1 4 1
# 9 26 4 120. 91 4.43 2.14 16.7 0 1 5 2
#10 30.4 4 95.1 113 3.77 1.51 16.9 1 1 5 2
#11 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2
Note that the output is different from the 1st value in cyl
column.
mtcars %>% filter(cyl == first(cyl))
# mpg cyl disp hp drat wt qsec vs am gear carb
#Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
#Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
#Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
#Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
#Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Upvotes: 4