emiliotorres · GitHub

Dear Sir,
sample_n does not respect the group_by variable. sample_frec works fine.
Best regards
Emilio

set.seed(123)
iris %>% sample_n(5) # OK
##     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 44           5.0         3.5          1.6         0.6     setosa
## 118          7.7         3.8          6.7         2.2  virginica
## 61           5.0         2.0          3.5         1.0 versicolor
## 130          7.2         3.0          5.8         1.6  virginica
## 138          6.4         3.1          5.5         1.8  virginica
set.seed(123)
ig <- iris %>% group_by(Species)
ig %>% sample_n(5) # Wrong! I expect 15 (5 x 3 levels of Species). But I get the same result
## Source: local data frame [5 x 5]
## Groups: Species
##     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 44           5.0         3.5          1.6         0.6     setosa
## 118          7.7         3.8          6.7         2.2  virginica
## 61           5.0         2.0          3.5         1.0 versicolor
## 130          7.2         3.0          5.8         1.6  virginica
## 138          6.4         3.1          5.5         1.8  virginica
set.seed(123)
ig %>% sample_frac(0.1) #OK
## Source: local data frame [15 x 5]
## Groups: Species

Read the original on github.com ↗