Skip to contents

Proportional or fixed stratified random sample

Usage

morie_stratified_sample(
  df,
  strata_col,
  n_per_stratum,
  proportional = FALSE,
  seed = 42L
)

Arguments

df

A data frame.

strata_col

Name of the stratification column.

n_per_stratum

Either an integer (equal allocation) or a named integer vector mapping stratum levels to sample sizes. If proportional = TRUE, n_per_stratum is treated as the total desired sample size and allocation is proportional to stratum size.

proportional

Logical; if TRUE, allocate proportionally to strata sizes.

seed

Random seed.

Value

Data frame of sampled rows with a .weight column.

Examples

df <- data.frame(g = c(rep("A", 60), rep("B", 40)), x = rnorm(100))
morie_stratified_sample(df, "g", n_per_stratum = 10)
#>    g           x .weight
#> 49 A  0.91643266       6
#> 37 A  0.97620252       6
#> 1  A -0.20196174       6
#> 25 A  0.54365786       6
#> 10 A  0.24919601       6
#> 36 A -0.30119698       6
#> 18 A  0.55989527       6
#> 60 A -0.40498716       6
#> 47 A  0.60430941       6
#> 24 A  0.26266524       6
#> 67 B  1.61662634       4
#> 96 B -0.25928910       4
#> 85 B -0.02516264       4
#> 97 B  0.33463227       4
#> 80 B  0.76728729       4
#> 86 B -0.16367334       4
#> 63 B -0.39000956       4
#> 98 B -1.42716761       4
#> 87 B  0.37005975       4
#> 64 B -1.81922223       4