Last active
April 1, 2021 14:22
-
-
Save ramhiser/8b5ffd0ffbfbf1f49e71bbbd330bf72d to your computer and use it in GitHub Desktop.
Stratified Sampling in R with dplyr
This file contains 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
# Uses a subset of the Iris data set with different proportions of the Species factor | |
set.seed(42) | |
iris_subset <- iris[c(1:50, 51:80, 101:120), ] | |
stratified_sample <- iris_subset %>% | |
group_by(Species) %>% | |
mutate(num_rows=n()) %>% | |
sample_frac(0.4, weight=num_rows) %>% | |
ungroup | |
# These results should be equal | |
table(iris_subset$Species) / nrow(iris_subset) | |
table(stratified_sample$Species) / nrow(stratified_sample) | |
# Success! | |
# setosa versicolor virginica | |
# 0.5 0.3 0.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have the same question as above-- any responses on this?