Using R we can generate either a single random integer, or a list of random integers. To do this we need to decide how many random numbers we want, the upper and lower bounds for our selections, and whether we want our selections to occur with or without replacement.
Example: Generate a single random integer between 1 and 10.
> sample(1:10, 1) [1] 4
Example: Generate a single random integer between 1 and 10, and store this number as x1. Then calculate 3*x1.
> x1 = sample(1:10, 1) > x1 [1] 10
> 3 * x1 [1] 30
Let's call this list rand.int. The default option for the sample command is to select values without replacement.
> rand.int = sample(1:20, 15) > rand.int [1] 6 2 16 8 9 5 18 14 15 11 10 19 12 3 1
Example: Generate a list of 15 randomly selected integers between 0 and 20, chosen with replacement.
Let's call this list rand.int.2. The default option for the sample command is to select values without replacement, so we will have to include the argument replace = TRUE.
> rand.int.2 = sample(1:20, 15, replace = TRUE) > rand.int.2 [1] 17 7 17 1 10 20 16 20 10 18 10 16 12 17 15
Random Real Numbers
The runif command is used to select random real numbers from the uniform distribution. We can choose to generate one or more random numbers between any upper and lower bounds.
Example: Generate a single random number between 2.2 and 3.5.
> runif(1, 2.2, 3.5) [1] 3.305643
Example: Generate a list of 10 randomly selected numbers between 1.75 and 10.82.
> runif(10, 1.75, 10.82) [1] 8.261552 8.159828 2.909501 8.097809 5.041455 9.397430 8.381366 9.432151 [9] 6.813843 6.762412
This list could also be stored, and called upon for later calculations.
Normal Random Numbers
The rnorm command is used to select random real numbers from the normal distribution. We can choose to generate one or more random numbers with a specified mean and standard deviation.
Example: Generate a single random number from the standard normal distribution.
For the standard normal distribution μ = 0 and σ = 1. These are the default values for the rnorm command.
> rnorm(1) [1] 1.201658
> rnorm(5) [1] -0.1209757 0.6925115 -0.6782760 -0.1545111 0.4656249
Example: Generate a list of 5 randomly selected numbers from a normal distribution with a mean of 15 and standard deviation of 3.2.
We will now need to add additional arguments to set μ = 15 and σ = 3.2.
> rnorm(5, mean = 15, sd = 3.2) [1] 10.43209 14.11475 18.60285 13.46017 14.58410
These values and lists could also be stored, and called upon for later calculations.
No comments:
Post a Comment