2

我想对值进行采样,但有一个约束要求两个值至少window分开。这类似于一年中的采样天数,但window至少相隔两周。到目前为止,我已经像这样尝试过

check.diff <- TRUE
window <- 14
while (check.diff == TRUE) {
    sampled.session <- sort(sample(1:365, size = 5, replace = FALSE))
    check.diff <- any(diff(sampled.session) < window)
}

如果window约束很小,这很有效。如果指定一个相当大的值,这可能会变成一个无限循环。虽然我可以插入各种检查和最大迭代次数,但我想知道是否有更聪明的方法来解决这个问题?

4

2 回答 2

2

一种方法是从您抽取样本的总体中删除候选人:

set.seed(42)

population <- 1:356
n_samples <- 5
window <- 14

sampled_session <- rep(sample(population, 1), n_samples) # initialize the vector

for (i in seq.int(2, n_samples)) {
    borders <- sampled_session[i - 1] + (window - 1) * c(-1, 1)
    days_in_window <- seq.int(borders[1], borders[2])
    population <- setdiff(population, days_in_window)
    sampled_session[i] <- sample(population, 1) 
}

sort(sampled_session)
# [1]  90 193 264 309 326

diff(sort(sampled_session))
# [1] 103  71  45  17

另一种方法是

set.seed(357)
population <- 1:357
n_samples <- 5
window <- 14

sampled.session <- numeric(n_samples) 
for (i in seq_len(n_samples)) {
    sampled.session[i] <- pick <- sample(population, 1)
    population <- population[-which(population < pick + window & population > pick - window)]
}
sort(sampled.session)
[1]  19  39 111 134 267
于 2012-12-07T12:33:32.040 回答
1

好吧,这样的事情怎么样。

window <- 14
sample_pair <- sample(1:365, size=2)
sample_pair[2] <- sample_pair[2] + window*(diff(foo)<window)

然后将该对转储到任何更大的样本组中。

或者,您可以在绘制后缩放整个样本集。伪代码:

samp.window <- diff(range(sample.set))
if (sample.window < window) sample.set <- sample.set *window/sample.window

如果需要,后跟一个round或。truncate可能值得检查以确保这些分布是均匀的:-(

于 2012-12-07T12:32:38.043 回答