Generate random numbers with fixed mean and sd

后端 未结 3 1411
渐次进展
渐次进展 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:08

    Since you asked for a one-liner:

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

提交回复
热议问题