我需要一个包含 300 个样本的随机分布,这些样本的值在 0 到大约 1 之间变化。 150.
此外,20% 的样本值应高于 50。
我尝试过这样的事情:
# my specifications
n <- 300 # fixed
percentage_above <- 0.2 # fixed
threshold <- 50 # fixed
lower <- 0 # fixed
upper <- 150 # fixed
m <- 35 # change
sd <- 45 # change
# truncated normal
samples <- rtruncnorm(n, a = lower, b = upper, m = m, sd = sd)
sum(samples > threshold) / n
根据我如何改变 m
和 sd
,我越来越接近所需的 20%。但是有没有更简单的方法来获得我需要的东西?
PS:底层分布不必是正态分布
最佳答案
这是一个基于指数分布的选项。它将生成n
个随机数,其中给定的比例prop
将大于给定的threshold
。如果 n
乘以比例是整数,则比例是准确的。
虽然它使用固定的随机种子,但它会将 R 的随机数生成器恢复到调用函数时的状态:
rnum <- function(n, prop = 0.2, threshold = 50, upper = 150) {
RS <- .GlobalEnv$.Random.seed
fun <- function(p) {
set.seed(1)
x <- rexp(n + 1)^p
x <- upper * x/max(x)
x <- x[-which.max(x)]
abs(sum(x > threshold)/n - prop)
}
p <- optimize(fun, c(0, 10))$minimum
set.seed(1)
x <- rexp(n + 1)^p
.GlobalEnv$.Random.seed <- RS
x <- upper * x/max(x)
x[-which.max(x)]
}
我们可以将输出视为直方图:
x <- rnum(300)
hist(x)
我们可以证明这些数字中有 20% 超过 50:
length(which(x > 50))
#> [1] 60
创建于 2023-07-08,使用 reprex v2.0.2
关于r - R 中的截断分布百分比高于特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76643138/