2016-09-06 7 views
0

繰り返しサンプリング値(A、B、A)を使用することは可能ですが、シーケンス(A、A、B)にすることはできません。単一値(A、A、A)または(B、B、B)。以下のコードは、少なくとも私に少なくとも2つの値を与えるはずですが、返される値が順番になることは望ましくありません。サンプリング値が連続していない

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

拒否サンプリングを使用することができます。拒否サンプリングが受け入れ可能かどうかを確認し、そうでない場合は再描画します。あなたはシーケンスの長さをチェックするためにrleを使用することができます。

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

size = 3について、あなたはおそらく一度か二度以上を描画する必要はありません。長いシーケンスでは、より洗練されたものを望むか​​もしれません。

+0

こんにちはニール、これは私が探していたものではないと思います。私は代わりに次のようにしました。それをよりエレガントにする方法があれば、私はそれを高く評価します。 – Sam

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 
+0

ありがとう!私は説明を書いた。私はそれが正しいことを願っています。 – Sam

関連する問題