Sample from vector of varying length (including 1)

This is a documented feature:

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x).

An alternative is to write your own function to avoid the feature:

sample.vec <- function(x, ...) x[sample(length(x), ...)]
sample.vec(10)
# [1] 10
sample.vec(10, 3, replace = TRUE)
# [1] 10 10 10

Some functions with similar behavior are listed under seq vs seq_along. When will using seq cause unintended results?

Leave a Comment