如何从多个列表(数字?

how to sample from multiple lists (numbers?

我想抽样,比方说100个65岁以上的人的年龄, 各年龄段的概率如下:

65-74<- 0.56
75-84<- 0.30
85<- 0.24

我知道示例函数的存在,我尝试了如下,但不幸的是没有用

list65_74<-range(65,74)
list75_84<-range(75,84)
list85<-range(85,100)

age<-sample(c(list65_74,list75_84,list85),size=10,replace=TRUE,prob =c(0.56,0.30,0.24 ))I get the following error

然后我得到了以下错误

 Error in sample.int(length(x), size, replace, prob) : 
      incorrect number of probabilities

所以我想知道从多个列表中抽样的正确方法是什么。 非常感谢您!

首先,让我们将这三个对象称为 groups,因为它们不使用 list 函数。

您定义它们的方式可能很好,但使用起来更直接,例如 65:74 而不是 c(65, 74)。所以,最终我把这三组放在下面的列表中:

groups <- list(group65_74 = 65:74, group75_84 = 75:84, group85 = 85:100)

现在使用 sample 的第一个问题是您的 x 参数值,即

either a vector of one or more elements from which to choose, or a positive integer. See ‘Details.’

与此同时,你 x 只是

c(list65_74, list75_84, list85)
# [1]  65  74  75  84  85 100

最后,prob的值不合适。您将 3 个数字提供给一个包含 6 个候选对象的向量以从中进行抽样。听起来不对。相反,您需要为每个组的每个年龄分配适当的概率,如

rep(c(0.56, 0.30, 0.24), times = sapply(groups, length))

所以结果是

sample(unlist(groups), size = 10, replace = TRUE, 
       prob = rep(c(0.56, 0.30, 0.24), times = sapply(groups, length)))
# [1] 82 72 69 74 72 72 69 70 74 70