Sam Sam - 3 months ago 19
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
print(b)

Answer

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.