Skip to content

Instantly share code, notes, and snippets.

@ericnovik
Created November 28, 2020 19:09
Show Gist options
  • Save ericnovik/24cc93e320350d1fb6373ee63c1b2dbf to your computer and use it in GitHub Desktop.
Save ericnovik/24cc93e320350d1fb6373ee63c1b2dbf to your computer and use it in GitHub Desktop.
# Avoids the following inconsitent behaviour from R's sample() function
# From the doc: 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). See the examples.
safe_sample <- function(x, ...) {
lx <- length(x)
if (lx == 1 & is.numeric(x)) {
as.numeric(sample(as.character(x), ...))
} else {
sample(x, ...)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment