R 采样值不按顺序排列

R 采样值不按顺序排列,r,random,sample,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 rep

是否可以进行采样,以便可以重复采样值(即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)

x您可以轻松使用拒绝采样,只需检查您的绘图是否可接受,如果不可接受,则重新绘制即可。您可以使用
rle
检查序列的长度:

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

a1)a您可以轻松地使用拒绝采样,只需检查您的绘图是否可接受,如果不可接受,则重新绘制即可。您可以使用
rle
检查序列的长度:

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

这个代码满足了我的需要。在这里,我将尝试解释

# 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
#抽取2个字母,不替换。
#信函样本总是不同的。

a这个代码适合我的需要。在这里,我将尝试解释

# 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
#抽取2个字母,不替换。
#信函样本总是不同的。

嗨,尼尔,我想这不是我想要的。我按照下面的方法做了。如果有更优雅的方式,我会非常感激。嗨,尼尔,我想这不是我想要的。我按照下面的方法做了。如果有更优雅的方式,我将不胜感激。谢谢!我已经把解释写下来了。我希望这是对的。谢谢!我已经把解释写下来了。我希望这是对的。