Select random element in a list of R?

后端 未结 6 1231
太阳男子
太阳男子 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))
      }
    }
    

提交回复
热议问题