--- title: "Vectors" author: "JJB + Course" date: "6/18/2018" output: html_document --- ## Example: Vector Types ```{r view-vectors} # Vector of numeric elements w = c(9.5, -3.14, 88.9999, 12.0) # ^ ^ ^ ^ decimals # Vector of integer elements x = c(1L, 2L, 3L, 4L) # Vector of logical elements y = c(TRUE, FALSE, FALSE, TRUE) # Vector of character elements z = c("a", "b", "c", "d") ``` ## Example: Writing and Calling Functions ```{r addition-function} # Function declaration add = function(a, b) { summed = a + b return(summed) } # Calling the function add(1, 2) ``` ## Example: Creating a Data Frame by Hand ```{r viewing-heights} subject_heights = data.frame( id = c(1, 2, 3, 55), sex = c("M", "F", "F", "M"), height = c(6.1, 5.5, 5.2, 5.9) ) ``` ## Example: Determine Class and Structure ```{r looking-into-data} class(subject_heights) str(subject_heights) ``` ## Example: Vectorization and Elements ```{r vectorized-addition} x = c(1, 2, 3, 4) y = c(5, 6, 7, 8) z = x + y z ``` ## Example: Vectorized Binary Operators ```{r example-of-ops} x = c(1, 2, 3, 4) y = c(5, 6, 7, 8) x + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division x ^ y # Exponentiation x %/% y # Integer Division x %% y # Modulus ``` ## Example: Recycling ```{r recycle-process} a = c(1, 2, 3, 4) length(a) b = c(5, 6, 7) length(b) a + b ``` ## Example: Recycling - Round 2 ```{r expansion-shorter} c(1, 2, 3, 4) + c(-1, 1) ``` ## Exercise: Determining Scalars Explain what happens if we have a vector and add a single value ```{r} a = 2 x = c(1, 2, 3, 4) x + a ``` ## Example: Everything is a Vector ```{r etia} a = 2 length(a) a_vec = c(2) length(a_vec) ``` ```{r eq-check} identical(a, a_vec) ``` ## Example: Positional Indexes ```{r ex-vector} ex_vec = c(5, 3, -2, 42) ``` ## Example: Retrieving a Single Value ```{r retrieve-first} ex_vec = c(5, 3, -2, 42) # Retrieve first element ex_vec[1] # Retrieve second element ex_vec[4] # Retrieve the nth element last_pos = length(ex_vec) ex_vec[last_pos] ``` ## Example: Retrieve Multiple Values ```{r retrieve-seq} ex_vec = c(5, 3, -2, 42) ex_vec[c(2, 3)] ex_vec[2:3] ``` ## Exercise: Positional Index Methods Using all sequence methods, create sequences for the following vectors. Are all approaches the same? ```{r} int_vec = c(8L, -2L, 5L, 0L) empty_vec = numeric(0) ```