Random number generators
R contains several functions to generate random numbers.
Type ?
function
in your console to get information on the function’s arguments (i.e. the values that must be provided to obtain the function’s result).
The function sample(x, n, replace = FALSE)
draws n
values from a given vector x
without replacement (by default).
Sampling without replacement means that when you repeatedly draw e.g. one item at a time from a pool of items, any item selected during the first draw is not available for selection during the second draw, and the first and second selected items are not in the pool to select from during the third draw, etc. Sampling with replacement means that all the original options are available at each draw.
YOUR TURN:
Sample 100 values between 3 and 103 with replacement. For this, open the R script(s) with the exercises (./exercise_script_with_solutions.R
and/or ./exercise_script_without_solutions.R
) from the root of your local repository, review the examples if needed, complete the exercise, and check out the proposed answer.
The following functions draw n
values from distributions with the specified parameters:
runif(n, min, max)
drawsn
values from a uniform distribution with the specifiedmin
andmax
.
rpois(n, lambda)
drawsn
values from a Poisson distribution with the specifiedlambda
.
rnorm(n, mean, sd)
drawsn
values from a normal distribution with the specifiedmean
and standard deviationsd
.
rbinom(n, prob)
drawsn
values from a binomial distribution with the specified probabilityprob
.
YOUR TURN:
1. Draw 100 values from a normal distribution with a mean of 0 and a standard deviation of 1.
2. Draw 50 values from a normal distribution with a mean of 10 and a standard deviation of 5.
3. Draw 1000 values from a Poisson distribution with a lambda of 50.
4. Draw 30 values from a uniform distribution between 0 and 10.
Try it out in your local exercise script.