r - 生成具有固定均值和标准差的随机数

标签 r random mean standard-deviation

当使用 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/

相关文章:

python - Pandas :估算 NaN 的

r - 有没有一种有效的方法来检查 R 字符向量是否包含相同的元素?

使用高度重复的键减少data.table的内存占用

c++ - xorshift128+ 算法的真正定义是什么?

node.js - MEAN 堆栈组件如何组合在一起?

r - 按组划分数据列

html - 计算 R 中前 10 名最常见作者的最佳方法

r - 使用 capture.output 捕获警告

javascript - 从 Javascript 对象中选择随机属性

java - 模拟股票价格