Jon*_*løv 20 random r mean standard-deviation
当使用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)
}
Run Code Online (Sandbox Code Playgroud)
为了显示:
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
Run Code Online (Sandbox Code Playgroud)
我想要这个的原因是我在将模拟数据应用于实际数据之前调整我的分析.这很好,因为模拟数据我知道确切的属性(平均值,SD等),我避免p值膨胀,因为我正在做推论统计.我问是否有任何简单的例如
rnorm(n=20, mean=5, sd=10, fixed=TRUE)
Run Code Online (Sandbox Code Playgroud)
Ben*_*ker 35
既然你要求一个单行:
rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
r <- rnorm2(100,4,1)
mean(r) ## 4
sd(r) ## 1
Run Code Online (Sandbox Code Playgroud)