Select random element in a list of R?

a<-c(1,2,0,7,5)

Some languages have a picker -function -- choose one random number from a -- how in R?

146779 次浏览
# Sample from the vector 'a' 1 element.
sample(a, 1)

Read this article about generating random numbers in R.

http://blog.revolutionanalytics.com/2009/02/how-to-choose-a-random-number-in-r.html

You can use sample in this case

sample(a, 1)

Second attribute is showing that you want to get only one random number. To generate number between some range runif function is useful.

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.

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))
}
}

An alternative is to select an item from the vector using runif. i.e

a <- c(1,2,0,7,5)
a[runif(1,1,6)]

Lets say you want a function that picks one each time it is run (useful in a simulation for example). So

a <- c(1,2,0,7,5)
sample_fun_a <- function() sample(a, 1)
runif_fun_a <- function() a[runif(1,1,6)]
microbenchmark::microbenchmark(sample_fun_a(),
runif_fun_a(),
times = 100000L)

Unit: nanoseconds

sample_fun_a() - 4665

runif_fun_a() - 1400

runif seems to be quicker in this example.

This method doesn't produce an error when your vector is length one, and it's simple.

a[sample(1:length(a), 1)]