Skip to content

Sample from this list

Source code

Description

Sample from this list

Usage

<Expr>$list$sample(
  n = NULL,
  ...,
  fraction = NULL,
  with_replacement = FALSE,
  shuffle = FALSE,
  seed = NULL
)

Arguments

n Number of items to return. Cannot be used with fraction.
Ignored.
fraction Fraction of items to return. Cannot be used with n. Can be larger than 1 if with_replacement is TRUE.
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.

Value

Expr

Examples

library("polars")

df = pl$DataFrame(
  values = list(1:3, NA_integer_, c(NA_integer_, 3L), 5:7),
  n = c(1, 1, 1, 2)
)

df$with_columns(
  sample = pl$col("values")$list$sample(n = pl$col("n"), seed = 1)
)
#> shape: (4, 3)
#> ┌───────────┬─────┬───────────┐
#> │ values    ┆ n   ┆ sample    │
#> │ ---       ┆ --- ┆ ---       │
#> │ list[i32] ┆ f64 ┆ list[i32] │
#> ╞═══════════╪═════╪═══════════╡
#> │ [1, 2, 3] ┆ 1.0 ┆ [3]       │
#> │ [null]    ┆ 1.0 ┆ [null]    │
#> │ [null, 3] ┆ 1.0 ┆ [3]       │
#> │ [5, 6, 7] ┆ 2.0 ┆ [6, 5]    │
#> └───────────┴─────┴───────────┘