What is a matrix and an array

11.0.1 S3 all the way!

Give a generic vector a dim attributes -> matrix

(A <- structure(1:6, dim = c(2, 3)))
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
class(A)
## [1] "matrix" "array"

Ok, but an array?:

(B <- structure(1:6, dim=6))
## [1] 1 2 3 4 5 6
class(B)
## [1] "array"

A matrix is a 2D array (which is a vector). The convention seems to be: give them a capital letter.

11.0.2 Not just numeric

Logical:

A >= 3
##       [,1] [,2] [,3]
## [1,] FALSE TRUE TRUE
## [2,] FALSE TRUE TRUE

Character:

matrix(strrep(LETTERS[1:6], 1:6), ncol=3)
##      [,1] [,2]   [,3]    
## [1,] "A"  "CCC"  "EEEEE" 
## [2,] "BB" "DDDD" "FFFFFF"

Even list:

matrix(list(1, 11:21, "A", list(1, 2, 3)), nrow=2)
##      [,1]       [,2]  
## [1,] 1          "A"   
## [2,] integer,11 list,3

Certain elements are not displayed correctly, but they are still there.

Internally elements are in column-major:

(B <- matrix(1:6, ncol=3, byrow=TRUE))
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
as.numeric(B)
## [1] 1 4 2 5 3 6

cool tip: you can name dimnames!

A <- structure(1:6, dim=c(2, 3), 
               dimnames=list(letters[1:2], LETTERS[1:3]))
names(dimnames(A)) <- c("ROWS", "COLUMNS")
print(A)
##     COLUMNS
## ROWS A B C
##    a 1 3 5
##    b 2 4 6