The Art of R Programming

(WallPaper) #1
Aszis still a vector, we can query its length:


length(z)
[1] 8



But as a matrix,zis a bit more than a vector:


class(z)
[1] "matrix"
attributes(z)
$dim
[1]42



In other words, there actually is amatrixclass, in the object-oriented pro-
gramming sense. As noted in Chapter 1, most of R consists of S3 classes,
whose components are denoted by dollar signs. Thematrixclass has one
attribute, nameddim, which is a vector containing the numbers of rows and
columns in the matrix. Classes will be covered in detail in Chapter 9.
You can also obtaindimvia thedim()function:



dim(z)
[1]42



The numbers of rows and columns are obtainable individually via the
nrow()andncol()functions:



nrow(z)
[1] 4
ncol(z)
[1] 2



These just piggyback ondim(), as you can see by inspecting the code.
Recall once again that objects can be printed in interactive mode by simply
typing their names:



nrow
function (x)
dim(x)[1]



These functions are useful when you are writing a general-purpose
library function whose argument is a matrix. By being able to determine
the number of rows and columns in your code, you alleviate the caller
of the burden of supplying that information as two additional arguments.
This is one of the benefits of object-oriented programming.


Matrices and Arrays 79
Free download pdf