间隔的连续整数的样本序列

时间:2017-12-05 15:12:15

标签: r random sample

我有一个关于采样的问题:我想在矢量中对连续数进行采样而不进行替换。有一个简单的方法吗? 例如,

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

给出10个介于1和100之间的数字。现在我希望有10个序列的3个连续整数而无需替换:c(2,3,4), c(10,11,12), c(82,83,84)等。

不同的序列不能重叠,即如果c(2,3,4)是我的第一次采样,那么以下任何一个都不能有这些数字。

我甚至会寻找对不同大小的10个序列进行采样的可能性,这些大小由像

这样的矢量给出
sizevec <- sample(c(1:4),10,replace = T)

感谢您的帮助

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您不清楚矢量是否重叠。假设可能重叠,这应该工作

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

具有随机长度将看起来像这样

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

答案 2 :(得分:0)

使用拖曳while循环取样的解决方案。运行代码后,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