Skip to content

Take a sample

Source code

Description

Take a sample

Usage

<Expr>$sample(
  frac = NULL,
  with_replacement = TRUE,
  shuffle = FALSE,
  seed = NULL,
  n = NULL
)

Arguments

frac Fraction of items to return (can be higher than 1). Cannot be used with n.
with_replacement If TRUE (default), allow values to be sampled more than once.
shuffle Shuffle the order of sampled data points (implicitly TRUE if with_replacement = TRUE).
seed numeric value of 0 to 2^52 Seed for the random number generator. If NULL (default), a random seed value between 0 and 10000 is picked.
n Number of items to return. Cannot be used with frac.

Value

Expr

Examples

library(polars)

df = pl$DataFrame(a = 1:4)
df$select(pl$col("a")$sample(frac = 1, with_replacement = TRUE, seed = 1L))
#> shape: (4, 1)
#> ┌─────┐
#> │ a   │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 3   │
#> │ 1   │
#> │ 1   │
#> │ 2   │
#> └─────┘
df$select(pl$col("a")$sample(frac = 2, with_replacement = TRUE, seed = 1L))
#> shape: (8, 1)
#> ┌─────┐
#> │ a   │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 3   │
#> │ 1   │
#> │ 1   │
#> │ 2   │
#> │ 2   │
#> │ 4   │
#> │ 1   │
#> │ 2   │
#> └─────┘
df$select(pl$col("a")$sample(n = 2, with_replacement = FALSE, seed = 1L))
#> shape: (2, 1)
#> ┌─────┐
#> │ a   │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 3   │
#> │ 1   │
#> └─────┘