相关疑难解决方法(0)

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

当使用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)  # …
Run Code Online (Sandbox Code Playgroud)

random r mean standard-deviation

20
推荐指数
1
解决办法
3万
查看次数

标签 统计

mean ×1

r ×1

random ×1

standard-deviation ×1