简体   繁体   中英

Randomly select a sample in R

I have to find a way to randomly choose a sample, in R, from the set S. The set S is composed by samples from I1 set.

I1 <- c(1,2,3,4,5,6)
s1 <- c(1,2,1)
s2 <- c(1,5,6)
s3 <- c(2,1,1)
s4 <- c(5,1,1,6)
s5 <- c(3,4)
s6 <- c(4,3) 

Every sample has a P value assigned from 0 to 1. I need to find the best way to generate a number from 0 to 1 and select the corresponding sample. This is what i did:

x <- runif(1, min = 0, max = 100) 
if(x>=0 & x<=20) {                
  print("s1")
}
if (x>=21 & x<=30) {
  print("s2")
}
if(x>=31 & x<=40) {
  print("s3")
}
if(x>=41 & x<=65) {
  print("s4")
}
if(x>=66 & x<=80) {
  print("s5")
}
if(x>=81 & x<=100) {
  print("s6")
}

Does anyone know a better way to do that ?

sample will be the easiest way. As I understand, you want to get name of the set?

If so, then use

sample(c('s1', 's2', 's3', 's4', 's5', 's6'), size = 1, prob = c(20, 10, 10, 25, 15, 20))

In case you want to get a set itself use list of sets as an object to draw from (you need to add [[1]] at the end of the statement):

sample(list(s1, s2, s3, s4, s5, s6), size = 1, prob = c(20, 10, 10, 25, 15, 20))[[1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM