当使用 Rnorm(或 runif 等)在 R 中生成随机数时,它们很少具有精确的平均值和 SD 作为它们采样的分布。有没有简单的一两行代码可以帮我做到这一点?作为初步解决方案,我创建了这个函数,但它似乎应该是 R 或某个包的 native 函数。
# 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)
最佳答案
既然你要求一句台词:
rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
r <- rnorm2(100,4,1)
mean(r) ## 4
sd(r) ## 1
关于r - 生成具有固定均值和标准差的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18919091/