# # Unit 7 - Vectorization # # Arithmetical and logical operations # # Problem: given a non-empty numeric # vector vec and a number num, # produce a new vector in which # num is added to each of vec's values. vec <- c(5, 4, 1) num <- 7 newVec <- c() for (val in vec) { newVec <- c(newVec, val + num) } print(newVec) # R offers a shortened code. # This is one example for vectorization, # specficially: vector with scalar vec1 <- c(5, 4, 1) resultVec <- vec1 + 1 print(resultVec) vec1 <- c(5, 4, 1) resultVec <- vec1 - 2 print(resultVec) vec1 <- c(5, 4, 1) resultVec <- vec1 * 3 print(resultVec) vec1 <- c(5, 4, 1) resultVec <- vec1 / 2 print(resultVec) vec1 <- c(5, 4, 1) resultVec <- vec1 ^ 2 print(resultVec) # Problem: given these two vectors # produce a new vector which is their # "sum", namely each value in it is # a sum of parallel values in the given # vectors. vec1 <- c(5, 4, 1) vec2 <- c(1, 1, 1) newVec <- c() for (ind in 1:length(vec1)) { newVec <- c(newVec, vec1[ind] + vec2[ind]) } print(newVec) # Using vectorization: vec1 <- c(5, 4, 1) vec2 <- c(1, 1, 1) resultVec <- vec1 + vec2 print(resultVec) vec1 <- c(5, 4, 1) vec2 <- c(1, 1, 1) resultVec <- vec1 - vec2 print(resultVec) vec1 <- c(5, 4, 1) vec2 <- c(1, 1, 1) resultVec <- vec1 * vec2 print(resultVec) vec1 <- c(5, 4, 1) vec2 <- c(1, 1, 1) resultVec <- vec1 / vec2 print(resultVec) # Now let us move to logical operations. # what would this code do? vec1 <- c(TRUE, FALSE, TRUE, TRUE) vec2 <- c(FALSE, FALSE, TRUE, TRUE) newVec <- vec1 & vec2 print(newVec) print(TRUE & FALSE) vec1 <- c(TRUE, FALSE, TRUE, TRUE) vec2 <- c(FALSE, FALSE, TRUE, TRUE) newVec <- vec1 | vec2 print(newVec) vec1 <- c(TRUE, FALSE, TRUE, TRUE) newVec <- !vec1 print(newVec) print(!TRUE) # %in%, scalar in vector vec <- c(1, 4, 1) print(5 %in% vec) # %in%, vector in vector vec1 <- c(1, 4, 1) vec2 <- c(1, 1, 1) result <- vec1 %in% vec2 print(result)