sample_data: Random sampling with optional stratification

View source: R/sample_data.R

sample_dataR Documentation

Random sampling with optional stratification

Description

Random sampling with optional stratification

Usage

sample_data(
  data,
  group = NULL,
  size = NULL,
  frac = NULL,
  replace = FALSE,
  seed = NULL,
  verbose = FALSE
)

Arguments

data

A data frame.

group

Grouping column.

size

Sample size per group (see Details).

frac

Sampling fraction per group (see Details).

replace

Sample with replacement.

seed

Random seed. If NULL, the current RNG state is used; if supplied, set.seed(seed) is called before sampling.

verbose

Logical.

Details

If group is NULL, either size (absolute number of rows) or frac (fraction of nrow(data)) must be supplied.

If group is provided, sampling is performed separately within each group. With size, every group contributes the same absolute number of rows (capped at the group's own size unless replace = TRUE). With frac, every group contributes its own round(frac * group_size) rows (at least 1), so groups of different sizes are sampled proportionally. If group is provided but both size and frac are NULL, each group contributes exactly one row.

Value

A sampled data frame.

Examples

sample_data(mtcars, frac = 0.5)
sample_data(mtcars, size = 3, group = "cyl", seed = 123)

# frac is per-group: large groups contribute more rows
n_by_cyl <- function(d) table(d$cyl)
n_by_cyl(sample_data(mtcars, frac = 0.5, group = "cyl", seed = 1))

dataprep documentation built on Oct. 1, 2026, 5:07 p.m.