R - Lecture 3
R - Lecture 3
Ivan Belik
• Example 1:
2
R: Matrix characteristics
• We can also check some characteristics:
dim(Matrix1) will give us: nrow(Matrix1) will give us: ncol(Matrix1) will give us:
> dim(Matrix1) > nrow(Matrix1) > ncol(Matrix1)
> [1] 3 3 [1] 3 [1] 3
3
R: Creating Matrices
• we can drop the argument names in matrix() as long as you remember that:
• Example 2:
• NA + 1 evaluates to NA
• NA == TRUE returns NA
4
R: Creating Matrices
• Example 3
Note: we did not use ncol argument (but, in the Example 3 the matrix with nrow=4 is the same one as with ncol=3)
5
R: Creating Matrices
• Example 4
6
R: Creating Matrices
• Example 4
7
R: Matrices
• As we could see, rbind() and cbind() functions automatically label row or column names
8
R: Matrices
9
R: Matrices
• The diag() function is useful for creating the identity matrix
10
R: Indexing matrices
• Use [i, j] to retrieve the j-th element of the i-th row:
byrow = FALSE by default – no need to specify it in the matrix()-function if we agree with the default value of the given parameter
11
R: Indexing matrices
• You can also extract entire rows as vectors by leaving the column entry blank, and vice versa
12
R: Matrix operations
• R can do matrix arithmetic. Below is a list of some basic operations we can do:
13
R: Matrix operations
14
R: Matrix operations
• To compute eigenvalues and vectors you can use the eigen() function
• Unlike most functions we have encountered so far, it does not return a vector or a matrix but a list
15
R: Matrix operations
• You can extract named elements from a list with the $ symbol
16
R: Lists and matrices
• We can use list() function to store vectors and matrices in one variable (which is a list-type):
17
R: Lists and matrices
• To access elements of the list:
18
R: Lists and matrices
• To access the list’s elements we can write one-line request:
19
R: Lists and matrices
• We can also assign names to the elements of the list
20
R: Lists: more details
• You can do different manipulations with variables in the lists:
21