collapse equivalent to dplyr::slice_head() ? · Issue #627 · SebKrantz/collapse (original) (raw)
Hi,
I'm wondering if there is a sort of equivalent to dplyr's slice_head() function in collapse:
Given the following data.frame, I would like to extract the first 2 rows grouped by id.
test_df <- data.frame(
id = sample(1:10, 20, replace = TRUE),
date = sample(seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "day"), 20)) %>%
roworder(id, date)
In dplyr the syntax probably would look something like:
result <- test_df %>%
arrange(id, date) %>%
group_by(id) %>%
slice_head(n = 2) %>%
ungroup()
and the result would contain the first two rows for each group (provided there are more than one row in a group - otherwise just the one row is return per group)
head(result)
# A tibble: 6 × 2
id date
<int> <date>
1 1 2023-01-05
2 1 2023-10-10
3 2 2023-05-26
4 2 2023-09-16
5 3 2023-12-30
6 4 2023-10-19