生成具有固定均值和 sd 的随机数 [英] Generate random numbers with fixed mean and sd
问题描述
当使用 rnorm
(或 runif
等)在 R 中生成随机数时,它们很少有精确的均值和 SD 作为采样的分布.有没有简单的一两个班轮为我做这件事?作为初步解决方案,我已经创建了这个函数,但它似乎应该是 R 或某些包的本机.
When generating random numbers in R using rnorm
(or runif
etc.), they seldom have the exact mean and SD as the distribution they are sampled from. Is there any simple one-or-two-liner that does this for me? As a preliminary solution, I've created this function but it seems like something that should be native to R or some package.
# 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 值膨胀,因为我正在做推论统计.我在问是否存在任何简单的东西,例如
The reason I want this is that I adjust my analysis on simulated data before applying it to real data. This is nice because with simulated data I know the exact properties (means, SDs etc.) and I avoid p-value inflation because I'm doing inferential statistics. I am asking if there exist anything simple like e.g.
rnorm(n=20, mean=5, sd=10, fixed=TRUE)
推荐答案
既然你要求单行:
rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
r <- rnorm2(100,4,1)
mean(r) ## 4
sd(r) ## 1
这篇关于生成具有固定均值和 sd 的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!