Select random element in a list of R?

R

R Problem Overview


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

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

R Solutions


Solution 1 - R

# Sample from the vector 'a' 1 element.
sample(a, 1)

Solution 2 - R

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 - R

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

Solution 4 - R

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

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

Solution 5 - R

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.

Solution 6 - R

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhhhView Question on Stackoverflow
Solution 1 - RDasonView Answer on Stackoverflow
Solution 2 - RmoldoveanView Answer on Stackoverflow
Solution 3 - RpomberView Answer on Stackoverflow
Solution 4 - RskanView Answer on Stackoverflow
Solution 5 - RChuck NorrisView Answer on Stackoverflow
Solution 6 - RMrHopkoView Answer on Stackoverflow