sample n rows by group from a table using the sample_n() function.

sample_n_by(data, ..., size = 1, replace = FALSE)

Arguments

data

a data frame

...

Variables to group by

size

the number of rows to select

replace

with or without replacement?

Examples

ToothGrowth %>% sample_n_by(dose, supp, size = 2)
#> # A tibble: 12 x 3 #> len supp dose #> <dbl> <fct> <dbl> #> 1 9.7 OJ 0.5 #> 2 17.6 OJ 0.5 #> 3 11.5 VC 0.5 #> 4 5.8 VC 0.5 #> 5 20 OJ 1 #> 6 26.4 OJ 1 #> 7 16.5 VC 1 #> 8 15.5 VC 1 #> 9 22.4 OJ 2 #> 10 24.8 OJ 2 #> 11 33.9 VC 2 #> 12 21.5 VC 2