生成具有固定均值和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
我想要这样做的原因是,在将模拟数据应用于实际数据之前,我会对其进行调整.很好,因为有了模拟数据,我就知道了确切的属性(均值,SD等),并且避免了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屋!