The Art of R Programming

(WallPaper) #1

test()
[,1] [,2]
[1,] 1 2
[2,] 0 2
[,1] [,2]
[1,] 3 2
[2,] 0 1
[,1] [,2]
[1,] 3 4
[2,] 0 2
[,1] [,2] [,3]
[1,]123
[2,]012
[3,]005
[,1] [,2] [,3]
[1,]432
[2,]012
[3,]001
[,1] [,2] [,3]
[1,]459
[2,]014
[3,]005



Throughout the code, we take into account the fact that the matrices
involved have a lot of zeros. For example, we avoid multiplying by zeros sim-
ply by not adding terms to sums when the terms include a 0 factor.
Theut()function is fairly straightforward. This function is aconstructor,
which is a function whose job it is to create an instance of the given class,
eventually returning that instance. So in line 9, we create a list that will serve
as the body of the class object, naming itrtrnas a reminder that this will be
the class instance to be constructed and returned.
As noted earlier, the main member variables of our class will bematand
idx, implemented as components of the list. Memory for these two compo-
nents is allocated in lines 11 and 12.
The loop that follows then fills inrtrn$matcolumn by column and
assignsrtrn$idxelement by element. A slicker way to do thisforloop would
be to use the rather obscurerow()andcol()functions. Therow()function
takes a matrix input and returns a new matrix of the same size, but with each
element replaced by its row number. Here’s an example:



m
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6



Object-Oriented Programming 217
Free download pdf