Josh O'Briens answer is a good way to do this, but doesn't provide much input validation. As I already wrote, he could also provide my answer. It's almost the same thing, but will take care of checking things as soon as you look at unique items and making sure there are enough unique items to ensure that you get at least one of them.
at_least_one_samp <- function(n, input){ # Only consider unique items. items <- unique(input) unique_items_count <- length(items) if(unique_items_count > n){ stop("Not enough unique items in input to give at least one of each") } # Get values for vector - force each item in at least once # then randomly select values to get the remaining. vals <- c(items, sample(items, n - unique_items_count, replace = TRUE)) # Now shuffle them sample(vals) } m <- c("a", "b", "c") at_least_one_samp(10, m)
Dason source share