I'm wondering if there is a version of sample() in R, whether built in or in a package, that always treats x as a vector to sample from rather than as an integer to samples numbers from 1 to x. My use case is using this programmatically where I don't want to get the second behaviour if x is of length 1.
Although a similar question was posted in Sample from vector of varying length (including 1), this doesn't answer if there is a solution bundled in a package. I've implemented a fix in my own function, but I am considering whether this is worth putting as a convenience function in a CRAN package? I want to know if someone has already solved this as a package.
sampleFrom <- function(x, size, replace = FALSE, ...) {
# Sometimes the input is only of length one, causing different behaviour
if(length(x) == 1) {
if(missing(size)){
return(x)
} else {
if(replace) {
return(rep(x, size))
} else {
# Deliberately run a command that will cause an error
# to get the error message while respecting copyright.
sample(1, 2, replace = FALSE)
}
}
}
sample(x, size, replace = replace, ...)
}