Return a sample from a vector within a grouping variable.

sample_bygroup(x, group, size = NULL, replace = FALSE)

Arguments

x

any vector

group

a grouping vector equal in length to length(x)

size

the number of items to sample within each group, as a positive number or a vector of numbers equal in length to the number of groups. If NULL, the sampling is stratified by group in the original group sizes.

replace

logical; should sampling be with replacement?

Value

x resampled within groups

Examples

set.seed(100) grvec <- c(rep("a", 3), rep("b", 4), rep("c", 3)) quanteda:::sample_bygroup(1:10, group = grvec, replace = FALSE)
#> [1] 2 1 3 7 6 4 5 9 10 8
quanteda:::sample_bygroup(1:10, group = grvec, replace = TRUE)
#> [1] 2 2 3 5 5 6 6 10 10 9
quanteda:::sample_bygroup(1:10, group = grvec, size = 2, replace = TRUE)
#> [1] 1 3 6 7 9 8
quanteda:::sample_bygroup(1:10, group = grvec, size = c(1, 1, 3), replace = TRUE)
#> [1] 2 6 9 8 10