1.1 Creating matrices in R
Create a \(3 \times 4\) matrix, meaning 3 row and 4 columns, that is all 1s:
matrix(1, 3, 4)
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
Create a \(3 \times 4\) matrix filled in with the numbers 1 to 12 by column (default) and by row:
matrix(1:12, 3, 4)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
matrix(1:12, 3, 4, byrow = TRUE)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
Create a matrix with one column:
matrix(1:4, ncol = 1)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
Create a matrix with one row:
matrix(1:4, nrow = 1)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
Check the dimensions of a matrix
= matrix(1:6, 2, 3)
A A
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
dim(A)
[1] 2 3
Get the number of rows in a matrix:
dim(A)[1]
[1] 2
nrow(A)
[1] 2
Create a 3D matrix (called array):
= array(1:6, dim = c(2, 3, 2))
A A
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
dim(A)
[1] 2 3 2
Check if an object is a matrix. A data frame is not a matrix. A vector is not a matrix.
= matrix(1:4, 1, 4)
A A
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
class(A)
[1] "matrix" "array"
= data.frame(A)
B B
X1 X2 X3 X4
1 1 2 3 4
class(B)
[1] "data.frame"
= 1:4
C C
[1] 1 2 3 4
class(C)
[1] "integer"