Random sample
resample.Rdbase::sample() treats a single numeric x with x >= 1 as 1:x and samples from that sequence.
This surprises callers when x may have varying length, such as in sample(x).
resample() always samples from the elements of x itself.
See base::sample() for more details.
Arguments
- x
(Atomic vector)
The atomic vector to sample from.- size
(Scalar integer:
[1, Inf))
The number of elements to sample.- replace
(Scalar logical)
Whether or not sampling should be done with replacement.- prob
(numeric:
NULL)
A non-negative numeric vector of lengthlength(x)whose elements sum to 1. Elementprob[i]is the probability of samplingx[i].NAvalues are not allowed.
Examples
#----------------------------------------------------------------------------
# resample() examples
#----------------------------------------------------------------------------
library(bkbase)
set.seed(2)
# Sample without replacement
resample(x = 1:10, size = 5)
#> [1] 5 6 9 1 10
# Sample with replacement
resample(x = c("a", "b", "c"), size = 5, replace = TRUE)
#> [1] "a" "a" "a" "b" "c"
# Weighted sampling
resample(
x = c("heads", "tails"),
size = 3, replace = TRUE,
prob = c(0.7, 0.3)
)
#> [1] "heads" "tails" "tails"
# A length-1 vector is sampled as-is, unlike base::sample()
resample(x = 5L, size = 1L)
#> [1] 5
sample(x = 5L, size = 1L) # samples from 1:5 instead
#> [1] 2