Matrix and array manipulations

11.0.3 what you know on indexing on data.frame works here

Get the book example:

(A <- matrix(1:12, byrow=TRUE, nrow=3))
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
(B <- `dimnames<-`(A, list(  
    c("a", "b", "c"),      
    c("x", "y", "z", "w") 
)))
##   x  y  z  w
## a 1  2  3  4
## b 5  6  7  8
## c 9 10 11 12
A[3, ] # rows
## [1]  9 10 11 12
A[, 2] # column
## [1]  2  6 10
B["c", "y"]  # specify dimnames
## [1] 10

By default drop is set to TRUE with [

A[1, 2, drop = FALSE]
##      [,1]
## [1,]    2

11.0.4 But behind the scene it is just a vector:

This works! :mind_blow:

A[6]
## [1] 10

11.0.5 Selecting by submatrices

It works, not going deep into it, but selecting on two columns numeric matrices is probably super useful.

It uses an index on row/column and return individual cells matching those “coordinates”.

On the same idea:

which(A>7, arr.ind=TRUE) #
##      row col
## [1,]   3   1
## [2,]   3   2
## [3,]   3   3
## [4,]   2   4
## [5,]   3   4

Return a “coordinate” matrix of cell that are matching a logical vector.

11.0.6 Higher-dimensional array (mostly know as contingency table)

str(dimnames(Titanic))
## List of 4
##  $ Class   : chr [1:4] "1st" "2nd" "3rd" "Crew"
##  $ Sex     : chr [1:2] "Male" "Female"
##  $ Age     : chr [1:2] "Child" "Adult"
##  $ Survived: chr [1:2] "No" "Yes"

hence (because it is “dimnmamed”) it works:

Titanic["1st", "Male", "Adult", "No", drop = FALSE]
## , , Age = Adult, Survived = No
## 
##      Sex
## Class Male
##   1st  118

But also with empty “space”:

Titanic["1st", , "Adult", ] 
##         Survived
## Sex       No Yes
##   Male   118  57
##   Female   4 140