Creating Vectors
27 Jan 2022In class today, I distributed the prompt for Problem Set 1. A digital version can be accessed here: ProblemSet1.pdf.
Vector Creation
We began with a review of basic assignment via the <-
operator and the c()
functions. Then we discussed the rep()
and seq()
functions.
# returns a new vector which repeats
# the vector letters two times
# the output itself is a vector of length 52 (i.e., 26x2)
rep(x = letters, times = 2)
# consider also the each argument
# it returns a new vector which repeats the
# 26 letters of the alphabet twice respectively
# try it out and compare to the above
rep(x = letters, each = 2)
Another useful function to create vectors is: seq()
. The seq()
function accepts three arguments:
from
to
by
orlength.out
It is used to create sequences from
some starting point to
some end point in increments one can specify with by
.
x <- seq(from = 0, to = 3, by = 0.5) # this creates a vector
# it is of length 7
# and contains the values: 0.0,
# 0.5, 1.0, 1.5, 2.0, 2.5, and
# 3.0
Alternatively you can create a sequence of a pre-specified length – say 5 – and let R figure out the correct increments.
y <- seq(from = 0, to = 3, length.out = 5) # this creates a vector
# it is of length 5
# and contains the values:
# 0.00, 0.75, 1.50, 2.25,
# and 3.00
Random Vectors
R contains a number of built-in functions for the creation of (quasi-) random vectors.
# a vector of 100 normally distributed numbers
# with mean 0 and standard deviation of 1
rnorm(n = 100, mean = 0, sd = 1)
# a vector of 100 uniformly distributed numbers
# on the interval from 0 to 1
runif(n = 100, min = 0, max = 1)
# a vector of 100 random number following the
# chi-square distribution with 15 degrees
# of freedom
rchisq(n = 10, df = 15)
# a vector of 99 random numbers following the
# student t distribution with 5 degrees
# of freedom
rt(n = 99, df = 5)
Sampling
The sample()
function allows us to generate vectors by drawing random samples from some target vector (or matrix). The code below, simulates a dice roll.
Dice <- c(1, 2, 3, 4, 5, 6)
# draws a sample of size 1 from the target vector: Dice
sample(x = Dice, size = 1)
The code below simulates 10 coin tosses.
Coin <- c("Heads", "Tails")
# draws a sample of size 10 with replacement
# from the target vector: Coin
sample(x = Coin, size = 10, replace = TRUE)