【发布时间】:2022-02-14 00:34:45
【问题描述】:
我试图了解 R 中 sample() 函数中的称重是如何工作的(概率参数)。
# seed
set.seed(123)
# some numbers
x = c(1:100)
# some probabilties
p = seq(from = 0, to = 1, length.out = 100)
# sample size
n = 10000
# sample 10000 times from x with probability p
x1 <- sample(x, size = n, replace = TRUE, prob = p)
# plot
hist(x1)
plot(density(x1))
现在这大概是概率论证的作用吗?
# adding weights manually
weight = rep(x, n * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)
# plot
hist(x2)
plot(density(x2))
编辑
我认为我在手动添加权重时犯了一个错误,即我使用了n*p,但我认为我应该使用x*p。然后结果确实有点变化:
# adding weights manually
weight = rep(x, x * p)
# now sample from the weighted vector
x2 <- sample(weight, n, replace = TRUE)
【问题讨论】:
-
“现在这大概就是概率论证的作用了吗?” - 取决于您所说的“大约”是什么意思。如果你的意思是如果它在功能上是等效的,那么答案是“是”。另一方面——如果你问代码是否做了类似的事情——答案几乎肯定是“不”。复制元素并不是一种非常有效的加权选择方式。
-
谢谢@JohnColeman - 这就是我一直在寻找的,即它是否在概念上相似。虽然我现在意识到我的称重尝试很糟糕。
-
了解
sample()在幕后所做的非常有用的答案:stackoverflow.com/a/59921493/4308815
标签: r