Select random element in a list of R?

后端 未结 6 1192
太阳男子
太阳男子 2020-12-29 19:19
a<-c(1,2,0,7,5)

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

相关标签:
6条回答
  • 2020-12-29 19:45

    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))
      }
    }
    
    0 讨论(0)
  • 2020-12-29 19:54

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

    a[sample(1:length(a),1)]
    
    0 讨论(0)
  • 2020-12-29 19:56

    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.

    0 讨论(0)
  • 2020-12-29 19:59

    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.

    0 讨论(0)
  • 2020-12-29 20:02

    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.

    0 讨论(0)
  • 2020-12-29 20:04
    # Sample from the vector 'a' 1 element.
    sample(a, 1)
    
    0 讨论(0)
提交回复
热议问题