Matrices

A matrix is like a vector, but in two dimensions. To enter a matrix in S-PLUS, enter a vector of data and the dimensions of the matrix. For example:

> matrix(c(1:9), nrow=3,ncol=3,byrow=T)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
In the above example, the ``by row'' argument tells S-PLUS to read the data in by row. The default is to read it by column, which would have resulted in:

> matrix(c(1:9),nrow=3,ncol=3)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
Vectors can be converted into matrices, by using the as.matrix function. This function changes a vector of length n into an n by 1 matrix. The as.vector function can be used to change a matrix into a vector (by reading down the columns, from left to right).

Matrices have two attributes: the dimensions of the matrix, and the names for the rows and columns.

> bulls <- matrix(c("Ron", "Michael", "Scottie", "Dennis", "Luc", "Steve", "Toni",
"Jud", "John", "Bill"), nrow=2, ncol=5, byrow=T)
> bulls
        [,1]      [,2]      [,3]     [,4]   [,5]
[1,] "Ron"   "Michael" "Scottie" "Dennis" "Luc"
[2,] "Steve" "Toni"    "Jud"     "John"   "Bill"
To check the dimensions of a matrix, use the function dim.

> dim(bulls)
[1] 2 5
Use the function dimnames to see or change the row and column names. Note that dimension names must be entered as a list (see next section).

> dimnames(bulls)
NULL
> dimnames(bulls) <- list(c("Starters","Bench"),c("PG","SG","SF","PF","C"))
> bulls
              PG        SG        SF       PF      C
Starters "Ron"   "Michael" "Scottie" "Dennis" "Luc"
   Bench "Steve" "Toni"    "Jud"     "John"   "Bill"
> dimnames(bulls)
[[1]]:
[1] "Starters" "Bench"

[[2]]:
[1] "PG" "SG" "SF" "PF" "C"



Pantelis Vlachos
1/15/1999