



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Warning in u + w: longer object length is not a. ## multiple of shorter object length. ## [1] 3 5 7 7 8. Add 1 to first element of u, add 2 to second.
Typology: Exams
1 / 27
This page cannot be seen from the preview
Don't miss anything!




















Lecture notes
This is (almost) all base R! We only need this for one thing later: library (tidyverse)
Define a vector, then “add 2” to it: u
k <- 2 u + k
adds 2 to each element of u.
As per linear algebra: k
u
k ***** u
Each element of vector multiplied by 2.
No error here (you get a warning). What happens? u
w <- c (1, 2) u + w
Add 1 to first element of u, add 2 to second. Go back to beginning of w to find something to add: add 1 to 3rd element of u, 2 to 4th element, 1 to 5th.
Keep re-using shorter vector until reach length of longer one. “Recycling”. If the longer vector’s length not a multiple of the shorter vector’s length, get a warning (probably not what you want). Same idea is used when multiplying a vector by a number: the number keeps getting recycled.
What happens if you add two matrices? A
B
A + B
Nothing surprising here. This is matrix addition as we and linear algebra know it.
Not matrix multiplication (as per linear algebra). Elementwise multiplication. Also called Hadamard product of A and B.
Like this: A
B
A %%* B
except that M is not an R matrix, and thus this doesn’t work: v <- c (1, 3) M %%* v
Do this first: M <- as.matrix (M)
and then all is good: M %%* v
To find the inverse of A: A
solve (A)
You can check that the matrix inverse and equation solution are correct.
Vectors in R are column vectors, so just do the matrix multiplication (t() is transpose): a <- c (1, 2, 3) b <- c (4, 5, 6) t (a) %%* b
Note that the answer is actually a 1 × 1 matrix. Or as the sum of the elementwise multiplication: sum (a ***** b)