只有 1 个数字的样本

Sample with only 1 number

我正在尝试创建一些模拟数据。为了创建聚类数据,我指定了处方医生是在一个还是多个地方卫生区 (LHA) 工作。现在,我正在尝试根据他们的 LHA 为患者分配处方。该代码位于以下代码块中。

for (i in seq_along(data$LHA)) {
  data$prescriber_id[i] <- sample(x = number_of_LHAs_worked$prescriber_id[
    number_of_LHAs_worked$assigned_LHAs_2 == data$LHA[i]], 
                                  size = 1)
}

这个循环适用于多个 LHA 的处方者(即给定样本函数的 x 的长度大于 1。但是,当处方者仅在一个 LHA 中工作时,由于样本的行为,它会失败函数。

sample(x = 154, size = 1) 

当x只给定一个数字时,R创建一个从1到x的索引,然后随机选择这个范围内的一个数字。

虽然我已经为我的目的制定了解决方案;我很想知道其他人是否想出了使示例函数更一致地工作的方法。具体来说,强制示例函数仅使用指定的集合。

sample(x = 154:155, size = 1)    # here the function chooses only a number in the set {154, 155}. 

?sample 在其示例中提供了答案:

set.seed(47)

resample <- function(x, ...) x[sample.int(length(x), ...)]

# infers 100 means 1:100
sample(100, 1)
#> [1] 98

# stricter
resample(100, 1)
#> [1] 100

# still works normally if explicit
resample(1:100, 1)
#> [1] 77