Creating Vectors; Indexing Vectors05 Feb 2018
Our code from class can be downloaded here: Code-Day05.R.
We began with a review of basic assignment via the
<- operator and the
c() functions. Introduced the
# returns a new vector which repeats # the vector pi ten times rep(x = pi, times = 10) # returns a new vector which repeats the # 26 letters of the alphabet 2 respectively rep(x = letters, each = 2)
Are 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)
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)
To extract individual elements or sub-vectors from a vector the
 notation can be used. Numbers of a vector of numbers supplied inside of the
 will instruct R to extract the objects located at the supplied position inside of the vector.
# extracts the element at position 26 of the vector letters # will return "z" letters # will return "h" letters # will return vector containing "h" and "z" letters[c(8, 26)] # will return vector containing "a", "b", and "c" letters[1:3] # will return letter "i" letters[8+1] # will return "d" Fourth_letter <- 4 letters[Fourth_letter] # will return vector of length 24 containing # all letters except "a" and "h" letters[-c(1,8)]
Last but not least we discussed the
which() function which returns a vector of index locations meeting a logical condition.
# evaluates to 8 and 17 which(letters == "h" | letters == "q")