在使用rnorm
(或runif
等)在 R 中生成随机数时,它们很少具有精确的均值和 SD 作为它们从中采样的分布。是否有任何简单的一两班轮可以为我做到这一点?作为初步解决方案,我已经创建了这个函数,但它似乎应该是 R 或某些包的原生函数。
# Draw sample from normal distribution with guaranteed fixed mean and sd
rnorm_fixed = function(n, mu=0, sigma=1) {
x = rnorm(n) # from standard normal distribution
x = sigma * x / sd(x) # scale to desired SD
x = x - mean(x) + mu # center around desired mean
return(x)
}
为了显示:
x = rnorm(n=20, mean=5, sd=10)
mean(x) # is e.g. 6.813...
sd(x) # is e.g. 10.222...
x = rnorm_fixed(n=20, mean=5, sd=10)
mean(x) # is 5
sd(x) # is 10
我想要这个的原因是我在将模拟数据应用到真实数据之前调整了我对模拟数据的分析。这很好,因为通过模拟数据,我知道确切的属性(均值、标准差等),并且我避免了 p 值膨胀,因为我正在做推论统计。我在问是否存在任何简单的东西,例如
rnorm(n=20, mean=5, sd=10, fixed=TRUE)