Select random element in a list of R?
Solution 1:
# Sample from the vector 'a' 1 element.
sample(a, 1)
Solution 2:
the above answers are technically correct:
sample(a, 1)
however, if you would like to repeat this process many times, let's say you would like to imitate throwing a dice, then you need to add:
a <- c(1,2,3,4,5,6)
sample(a, 12, replace=TRUE)
Hope it helps.
Solution 3:
Be careful when using sample!
sample(a, 1)
works great for the vector in your example, but when the vector has length 1 it may lead to undesired behavior, it will use the vector 1:a
for the sampling.
So if you are trying to pick a random item from a varying length vector, check for the case of length 1!
sampleWithoutSurprises <- function(x) {
if (length(x) <= 1) {
return(x)
} else {
return(sample(x,1))
}
}