Sam Sam - 1 year ago 92
R Question

Sampling values not in sequence

Is it possible to sample such that it is Okay to have repeated sampling values (i.e. A,B,A ), but it cannot be in sequence(A,A,B), or return just one single value (A,A,A) or (B,B,B). The code below should always give me at least two values, but I don't want the returned values to be in sequence.

x<- 3
alphabet <- LETTERS[seq(1:26)]
a <- sample(alphabet, 2, replace = FALSE)
b <- sample(a, x, replace = TRUE, prob=c(0.5,0.5)) #can't replace

Answer Source

You could easily use rejection sampling, just by checking if your draw is acceptable and redrawing if not. You can use rle to check lengths of sequences:

a <- sample(letters, 3, replace=TRUE)
while(any(rle(a)$lengths > 1)) a <- sample(letters, 3, replace=TRUE);

For size = 3, you probably won't have to draw more than once or twice; for longer sequences, you might want something more sophisticated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download