Generate random numbers with fixed mean and sd

后端 未结 3 1407
渐次进展
渐次进展 2020-11-27 16:58

When generating random numbers in R using rnorm (or runif etc.), they seldom have the exact mean and SD as the distribution they are sampled from.

3条回答
  •  臣服心动
    2020-11-27 17:27

    The mvrnorm() function in the MASS package can do this.

    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)
    

提交回复
热议问题