Created
November 28, 2020 19:09
-
-
Save ericnovik/24cc93e320350d1fb6373ee63c1b2dbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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