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 14.5 OJ 0.5 #> 2 8.2 OJ 0.5 #> 3 5.2 VC 0.5 #> 4 7 VC 0.5 #> 5 27.3 OJ 1 #> 6 25.8 OJ 1 #> 7 22.5 VC 1 #> 8 13.6 VC 1 #> 9 24.8 OJ 2 #> 10 30.9 OJ 2 #> 11 23.3 VC 2 #> 12 18.5 VC 2