区间连续整数的样本序列

sample sequence of successive integer of an interval

我有一个关于采样的问题:我想对一个向量中的连续数字进行采样而不用放回。有没有一种简单的方法可以做到这一点? 例如,

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

给了我 1 到 100 之间的 10 个数字。现在我想要 10 个连续的 3 个整数序列而无需替换:c(2,3,4), c(10,11,12), c(82,83,84)

不同的序列不能重叠,也就是说如果c(2,3,4)是我的第一个样本,那么后面的none可以有这些数字。

我什至会寻找对 10 个不同大小的序列进行采样的可能性,这些大小由向量给出

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

感谢帮助

您好,您不清楚向量是否重叠。假设可能重叠这应该有效

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})

使用两个 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
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