生成具有固定均值和sd的随机数

时间:2013-09-20 14:22:08

标签: r random 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)
}

举例说明:

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值膨胀,因为我正在做推论统计。我在问是否有任何简单的例如。

rnorm(n=20, mean=5, sd=10, fixed=TRUE)

3 个答案:

答案 0 :(得分:32)

因为你要求一个单行:

rnorm2 <- function(n,mean,sd) { mean+sd*scale(rnorm(n)) }
r <- rnorm2(100,4,1)
mean(r)  ## 4
sd(r)    ## 1

答案 1 :(得分:2)

MASS软件包中的mvrnorm()函数可以做到这一点。

library(MASS)
#empirical=T forces mean and sd to be exact
x <- mvrnorm(n=20, mu=5, Sigma=10^2, empirical=T)
mean(x)
sd(x)
#empirical=F does not impose this constraint
x <- mvrnorm(n=20, mu=5, Sigma=10^2, empirical=F
mean(x)
sd(x)

答案 2 :(得分:1)

这是对前一个答案中建议的功能的改进,因此它符合OP需要具有&#34;固定&#34;论点。

仍然在一行; - )

rnorm. <- function(n=10, mean=0, sd=1, fixed=TRUE) { switch(fixed+1, rnorm(n, mean, sd), as.numeric(mean+sd*scale(rnorm(n)))) }
rnorm.() %>% {c(mean(.), sd(.))}
#### [1] 0 1
rnorm.(,,,F) %>% {c(mean(.), sd(.))}
#### [1] 0.1871827 0.8124567

我选择为每个参数输入默认值,并添加as.numeric步骤以消除scale函数生成的属性。

相关问题