Press "Enter" to skip to content

Matrices In R

Dave Mason continues his perusal of R data types, this time looking at the matrix:

All of the examples so far have consisted of matrices with data elements of the same class. And for good reason: it’s a requirement for a matrix. R will coerce elements with mismatched classes to the same class. Here are two vectors, one of class integer and the other of class character. After combining them into a matrix via rbind(), we see the first row of data elements are of the character class (enclosed in double quotes):

> row1 <- c(1L, 2L, 3L, 4L)
> row2 <- c("a", "b", "c", "d")
> new_matrix <- rbind(row1, row2)
> new_matrix [,1] [,2] [,3] [,4]
row1 "1" "2" "3" "4"
row2 "a" "b" "c" "d"

Matrices drive a large number of statistical techniques, though I tend to deal with them less directly than I would have imagined.