Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers with fixed mean and sd

Tags:

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. Is there any simple one-or-two-liner that does this for me? As a preliminary solution, I've created this function but it seems like something that should be native to R or some package.

# 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) } 

To illustrate:

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 

The reason I want this is that I adjust my analysis on simulated data before applying it to real data. This is nice because with simulated data I know the exact properties (means, SDs etc.) and I avoid p-value inflation because I'm doing inferential statistics. I am asking if there exist anything simple like e.g.

rnorm(n=20, mean=5, sd=10, fixed=TRUE) 
like image 728
Jonas Lindeløv Avatar asked Sep 20 '13 14:09

Jonas Lindeløv


People also ask

How do you generate random numbers with mean and standard deviation in R?

Random numbers from a normal distribution can be generated using rnorm() function. We need to specify the number of samples to be generated. We can also specify the mean and standard deviation of the distribution. If not provided, the distribution defaults to 0 mean and 1 standard deviation.

How do you generate a random number with mean and standard deviation in Excel?

Use the formula "=NORMINV(RAND(),B2,C2)", where the RAND() function creates your probability, B2 provides your mean and C2 references your standard deviation. You can change B2 and C2 to reference different cells or enter the values into the formula itself.

How does Matlab generate random numbers with mean and standard deviation?

r = normrnd( mu , sigma ) generates a random number from the normal distribution with mean parameter mu and standard deviation parameter sigma . r = normrnd( mu , sigma , sz1,...,szN ) generates an array of normal random numbers, where sz1,...,szN indicates the size of each dimension.


1 Answers

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 
like image 64
Ben Bolker Avatar answered Oct 16 '22 08:10

Ben Bolker