Created
February 19, 2022 12:15
-
-
Save janfreyberg/8784cab1f5a79f15f5c840aa9763de2b to your computer and use it in GitHub Desktop.
Sample groups in a tidy data frame.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.