Sample Random Numbers with Fixed Mean & Standard Deviation in R (Example Code)

In this tutorial, I’ll explain how to sample random numbers with fixed mean and standard deviation in the R programming language.

Example: Generating Random Values with Fixed Mean & Standard Deviation

my_mean <- 7              # Specifying parameters
my_sd <- 4
my_samplesize <- 20
set.seed(89356483)        # Sampling random data
my_rand <- as.vector(my_mean + my_sd * scale(rnorm(my_samplesize)))
my_rand
#  [1]  8.5006439  8.1654572 -0.1500976  2.8101344  0.2169770  6.4610640
#  [7]  7.2558598  7.4011032 13.8625799  8.1255807 10.9492783  1.3295415
# [13]  7.9738863 13.2263514  4.6041523  7.6225218  8.6066314  2.6271294
# [19]  9.5079960 10.9032091
mean(my_rand)             # Mean of randomly generated data
# [1] 7
sd(my_rand)               # Standard deviation of randomly generated data
# [1] 4

Related Tutorials

Have a look at the following R tutorials. They illustrate topics such as variables, missing data, and descriptive statistics.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top