The Art of R Programming

(WallPaper) #1

14.2.3 Extended Example: Generating a Powers Matrix...................


Recall in Section 9.1.7, we needed to generate a matrix of powers of our pre-
dictor variable. We used the following code:

1 # forms matrix of powers of the vector x, through degree dg
2 powers1 <- function(x,dg) {
3 pw <- matrix(x,nrow=length(x))
4 prod <- x # current product
5 for (i in 2:dg) {
6 prod <- prod*x
7 pw <- cbind(pw,prod)
8 }
9 return(pw)
10 }

One glaring problem is thatcbind()is used to build up the output ma-
trix, column by column. This is very costly in terms of memory-allocation
time. It’s much better to allocate the full matrix at the beginning, even
though it will be empty, as this will mean incurring the cost of only one
memory-allocation operation.

1 # forms matrix of powers of the vector x, through degree dg
2 powers2 <- function(x,dg) {
3 pw <- matrix(nrow=length(x),ncol=dg)
4 prod <- x # current product
5 pw[,1] <- prod
6 for (i in 2:dg) {
7 prod <- prod*x
8 pw[,i] <- prod
9 }
10 return(pw)
11 }

And indeed,powers2()is a lot faster.

> x <- runif(1000000)
> system.time(powers1(x,8))
user system elapsed
0.776 0.356 1.334
> system.time(powers2(x,8))
user system elapsed
0.388 0.204 0.593

312 Chapter 14

Free download pdf