提取某些级别比其他级别更多

Extracting certain levels more than others

我正在尝试模拟从给定站点对野生动物进行采样。我制作了一个物种列表,其中包含可以在该站点找到的所有物种及其相关的稀有度。

df <- data.frame(rarity = rep(c('common', 'uncommon', 'rare'), each = 2),
                 species = letters[1:6])
print(df)
    rarity species
1   common       a
2   common       b
3 uncommon       c
4 uncommon       d
5     rare       e
6     rare       f

然后我根据 df.

中行的随机抽样创建另一个数据集
df.sampled <- df[sample(1:nrow(df), 30, T),]

问题是这不现实;您遇到 rare 个物种的频率不会像 uncommon 个物种和 common 个物种一样频繁。例如,遇到的10只动物中有6只应该是common,10只动物中有3只应该是uncommon,10只动物中有1只应该是rare。在这里,我们以相同的频率获得所有三种稀有度:

df.matrix <- matrix(NA, ncol = 3, nrow = 1000)
for(i in 1:1000){
  df.sampled <- df[sample(1:6, 30, T),]
  df.matrix[i,] <- c(table(df.sampled$rarity))
}
apply(df.matrix, 2, mean)

鉴于它们的稀有性,有没有一种方法可以让我比其他行更频繁地对特定行进行采样?我感觉应该使用 qnorm(),但我可能错了...

这是你编辑的行以使用 prob 参数,示例值 0.6 表示常见,0.3 表示不常见,0.1 表示罕见:

prob_vec <- c(0.6, 0.6, 0.3, 0.3, 0.1, 0.1)
df.sampled <- df[sample(1:nrow(df), 30, T, prob = prob_vec),]

df.sampled 现在分布更加不均匀。