Select random element in a list of R?

后端 未结 6 1222
太阳男子
太阳男子 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: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.

提交回复
热议问题