我正在尝试创建一些模拟数据。为了创建聚类数据,我已指定处方者是否在一个或多个本地卫生区域 (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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)