2017-12-05 9 views
1

サンプリングに関する質問があります:ベクトルの連続番号を置換せずにサンプリングしたいと思います。そうする簡単な方法はありますか?例えば、区間の連続する整数のサンプルシーケンス

sample(c(1:100), 10, replace = F) 
76 99 94 53 12 34 5 82 75 30 

が今は交換することなく、3つの連続する整数の10配列したいと思う私に1〜100の10数を与える :c(2,3,4), c(10,11,12), c(82,83,84)

異なる配列が重複しないことができ、つまり、c(2,3,4)が最初のサンプリングである場合、次のいずれの番号もこれらの番号を持つことはできません。

私もベクトルが重複する可能性がある場合、ヘルプ

答えて

0

サンプルを取るためにトウwhileループを使用して溶液のようになり有する

lapply(sample(c(1:97), 10, replace = F),function(i){ 0:2 + i}) 

を動作するはず重なっていてもよいと仮定。コードを実行した後、xは望ましい出力のリストです。

# Set seed for reproduciblility 
set.seed(123) 

# Create a list to store values 
x <- list() 
# Create a vector to store values in x 
y <- integer() 

# Set the threshold to stop 
threshold <- 4 

# Set the condition 
condition <- TRUE 

while (length(x) < threshold){ 
    while (condition){ 
    # Sample a number between 1 to 98 
    s <- sample(c(1:98), 1) 
    # Create a sequence 
    se <- s:(s + 2) 
    # Check if the values in se is in y, save it to the condition 
    condition <- any(se %in% y) 
    } 
    # Save se to the list 
    x[[length(x) + 1]] <- se 
    # Update y 
    y <- unlist(x) 
    # Reset the condition 
    condition <- TRUE 
} 

# View the results 
x 
# [[1]] 
# [1] 29 30 31 
# 
# [[2]] 
# [1] 79 80 81 
# 
# [[3]] 
# [1] 41 42 43 
# 
# [[4]] 
# [1] 89 90 91 
+1

はい、うまくいきます。私は今までより良い解決策を見いだせなかった。あなたの助けと時間をありがとう – denis

+0

@denis私はすべての値が1から100の間であることを確認するために 'sample(c(1:100)、1)'を 'sample(c(1:98)、1)'に変更することにしました。 – www

0

のおかげでは、HIあなたが不明である、異なるサイズの10列、

sizevec <- sample(c(1:4),10,replace = T) 

のようなベクトルによって与えられた大きさをサンプリングの可能性を探しますか否か。これは、ランダムな長さは、この

lapply(sample(c(1:97), 10, replace = F),function(i){ 0:sample(1:10,1) + i}) 
+0

実は私は彼らが重ならないようにしたいと思います。申し訳ありません、私の質問を編集しました – denis

2
set.seed(42) 
lapply(sample(1:10, 1) + cumsum(sample(4:10, 10, TRUE)), function(x) x + 1:3) 
# [[1]] 
# [1] 21 22 23 

# [[2]] 
# [1] 27 28 29 

# [[3]] 
# [1] 36 37 38 

# [[4]] 
# [1] 44 45 46 

# [[5]] 
# [1] 51 52 53 

# [[6]] 
# [1] 60 61 62 

# [[7]] 
# [1] 64 65 66 

# [[8]] 
# [1] 72 73 74 

# [[9]] 
# [1] 80 81 82 

# [[10]] 
# [1] 87 88 89 
関連する問題