Functions: Generating Random Data Flashcards
sample()
From the integers 1:10, draw 5 numbers
function allows you to draw random samples of elements (scalars) from a vector.
sample(x = 1:10, size = 5)
##[1] 6 3 7 10 4
sample(x = 1:5, size = 10, replace = TRUE)
##[1] 4 1 4 3 5 2 1 2 4 4
If you don’t specify the replace argument, R will assume that you are sampling without replacement. In other words, each element can only be sampled once.
probability argument
in sample(), To specify how likely each element in the vector x should be selected, use the prob argument. The length of the prob argument should be as long as the x argument. For example, let’s draw 10 samples (with replacement) from the vector [“a”, “b”], but we’ll make the probability of selecting “a” to be .90, and the probability of selecting “b” to be .10
sample(x = c(“a”, “b”),
prob = c(.9, .1),
size = 10,
replace = TRUE)
rnorm()
5 samples from a Normal dist with mean = 0, sd = 1
to generate samples from a normal distribution
rnorm(n = 5, mean = 0, sd = 1)
uniform distribution
gives equal probabilities to all values between its minimum and maximum
runif()
5 samples from Uniform dist with bounds at 0 and 1
To generate samples from a uniform distribution, use the function runif(), the function has 3 arguments:
runif(n = 5, min = 0, max = 1)