Matrices

There are several ways of making a matrix. You can create one directly like this:

X<-matrix(c(1,0,0,0,1,0,0,0,1),nrow=3)

X

      [,1]     [,2]     [,3]
[1,]     1        0        0
[2,]     0        1        0
[3,]     0        0        1

where, by default, the numbers are entered columnwise. The class and attributes of X indicate that it is a matrix of three rows and three columns (these are its dim attributes)

class(X)

[1]  "matrix"

attributes(X)

$dim

[1]  3  3

In the next example, the data in the vector appear row-wise, so we indicate this with byrow=T:

vector<-c(1,2,3,4,4,3,2,1)
V<-matrix(vector,byrow=T,nrow=2)
V

     [,1]     [,2]     [,3]     [,4]
[1,]    1        2        3        4
[2,]    4        3        2        1

Another way to convert a vector into a matrix is by providing the vector object with two dimensions (rows and columns) using the dim function like this:

dim(vector)<-c(4,2)

We can check that vector has now become a matrix:

is.matrix(vector)

[1] TRUE

We need to be careful, however, because we have made no allowance at this stage for the fact that the data were entered row-wise into vector:

vector

     [,1]     [,2]
[1,]    1        4
[2,]    2        3
[3,]    3        2
[4,]    4        1

The matrix we want is the transpose, t, of this matrix:

(vector<-t(vector))

      [,1]     [,2]     [,3]     [,4]
[1,]     1        2        3        4
[2,]     4        3        2        1

Naming the rows and columns of matrices

At first, matrices have numbers naming their rows and columns (see above). Here is a 4 ×5 matrix of random integers from a Poisson distribution with mean= 1.5:

X<-matrix(rpois(20,1.5),nrow=4)
X [,1] [,2] [,3] [,4] [,5] [1,] 1 0 2 5 3 [2,] 1 1 3 1 3 [3,] 3 1 0 2 2 [4,] 1 ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.