Skip to content

Take a sample

Source code

Description

Take a sample

Usage

<Expr>$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(a = 1:4)
df$select(pl$col("a")$sample(fraction = 1, with_replacement = TRUE, seed = 1L))
#> shape: (4, 1)
#> ┌─────┐
#> │ a   │
#> │ --- │
#> │ i32 │
#> ╞═════╡
#> │ 3   │
#> │ 1   │
#> │ 1   │
#> │ 2   │
#> └─────┘
df$select(pl$col("a")$sample(fraction = 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   │
#> └─────┘