采样值不按顺序

Sampling values not in sequence

是否可以进行采样,这样可以重复采样值(即 A,B,A ),但不能按顺序排列(A,A,B),或者 return 只是一个值 (A,A,A) 或 (B,B,B)。下面的代码应该总是给我至少两个值,但我不希望 returned 值按顺序排列。

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)

您可以轻松地使用拒绝抽样,只需检查您的抽签是否可以接受,如果不接受则重新抽取。您可以使用 rle 检查序列的长度:

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

对于size = 3,您可能不需要画超过一两次;对于更长的序列,您可能需要更复杂的东西。

这段代码满足了我的需要。在这里我会尽量解释一下。

# sample 2 letters without replacement. 
# The sample letter will always be different.
a <- sample(LETTERS, 2, replace = FALSE) 

# sample 3 times randomly. 
b <- sample(a, 3, replace=TRUE)

# Reject sampling and repeat again if all the sampled values are the same.
# b %in% b[duplicated(b)]) return duplicated as TRUE, non duplicated as FALSE
# sort(unique(b %in% b[duplicated(b)])) returns only TRUE if the sample result consists of 1 sampled value. Keep doing that unless returns FALSE in the first position. 

while(sort(unique(b %in% b[duplicated(b)]))[1] == TRUE){
  b <- sample(a, x, replace=TRUE);
}
b