Skip to content

Instantly share code, notes, and snippets.

@janfreyberg
Created February 19, 2022 12:15
Show Gist options
  • Save janfreyberg/8784cab1f5a79f15f5c840aa9763de2b to your computer and use it in GitHub Desktop.
Save janfreyberg/8784cab1f5a79f15f5c840aa9763de2b to your computer and use it in GitHub Desktop.
Sample groups in a tidy data frame.
sample_groups <- function(.data, ..., n, prop) {
slice_size <- dplyr:::check_slice_size(n, prop)
.data %>%
dplyr::group_by(...) %>%
tidyr::nest() %>%
dplyr::ungroup() %>%
{
if (slice_size$type == "n") {
dplyr::slice_sample(., n=slice_size$n)
} else {
dplyr::slice_sample(., prop=slice_size$prop)
}
} %>%
tidyr::unnest(data)
}
@janfreyberg
Copy link
Author

This function samples from groups of a dataframe. It groups by the grouping columns, samples groups, and then ungroups. The number of groups can be specified as either a number or a proportion, similar to dplyr::slice_sample.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment