采样值不按顺序排列

时间:2016-09-06 21:47:55

标签: r random sample

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

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)

2 个答案:

答案 0 :(得分:2)

您可以轻松地使用拒绝抽样,只需检查您的抽奖是否可以接受,否则重绘。您可以使用rle来检查序列的长度:

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

对于size = 3,您可能不必画一次或两次以上;对于更长的序列,您可能想要更复杂的东西。

答案 1 :(得分:0)

此代码适用于我的需求。在这里,我将尝试解释。

# 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