The Art of R Programming

(WallPaper) #1
> row(m)
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3

Thecol()function works similarly.
Using this idea, we could replace theforloop inut()with a one-liner:

rtrn$mat <- inmat[row(inmat) <= col(inmat)]

Whenever possible, we should exploit vectorization. Take a look at
line 12, for example:

rtrn$ix <- sum1toi(0:(n-1)) + 1

Sincesum1toi()(which we defined on line 4) is based only on the vector-
ized functions"*"()and"+"(),sum1toi()itself is also vectorized. This allows
us to applysum1toi()to a vector above. Note that we used recycling as well.
We want our"ut"class to include some methods, not just variables. To
this end, we have included three methods:


  • Theexpandut()function converts from a compressed matrix to an ordi-
    nary one. Inexpandut(), the key lines are 27 and 28, where we usertrn$ix
    to determine where inutmat$matthejthcolumn of our matrix is stored.
    That data is then copied to thejthcolumn offullmatin line 30. Note the
    use ofrep()to generate the zeros in the lower portion of this column.

  • Theprint.ut()function is for printing. This function is quick and easy,
    usingexpandut(). Recall that any call toprint()on an object of type"ut"
    will be dispatched toprint.ut(), as in our test cases earlier.

  • The"%mut%"()function is for multiplying two compressed matrices (with-
    out uncompressing them). This function starts in line 39. Since this is
    a binary operation, we take advantage of the fact that R accommodates
    user-defined binary operations, as described in Section 7.12, and imple-
    ment our matrix-multiply function as%mut%.


Let’s look at the details of the"%mut%"()function. First, in line 43,
we allocate space for the product matrix. Note the use of recycling in an
unusual context. The first argument ofmatrix()is required to be a vector
of a length compatible with the number of specified rows and columns, so
the 0 we provide is recycled to a vector of lengthn^2. Of course,rep()could
be used instead, but exploiting recycling makes for a bit shorter, more ele-
gant code.
For both clarity and fast execution, the code here has been written
around the fact that R stores matrices in column-major order. As mentioned
in the comments, our code then makes use of the fact that columniof the

218 Chapter 9

Free download pdf