The Art of R Programming

(WallPaper) #1
R informed us here that, from a vector-indexing point of view, elements
1, 3, 5, and 6 ofmare larger than 2. For example, element 5 is the element in
row 2, column 2 ofm, which we see has the value 10, which is indeed greater
than 2.

3.2.5 Extended Example: Generating a Covariance Matrix...............


This example demonstrates R’srow()andcol()functions, whose arguments
are matrices. For example, for a matrixa,row(a[2,8])will return the row
number of that element ofa, which is 2. Well, we knewrow(a[2,8])is in row
2, didn’t we? So why would this function be useful?
Let’s consider an example. When writing simulation code for multi-
variate normal distributions—for instance, usingmvrnorm()from theMASS
library—we need to specify a covariance matrix. The key point for our pur-
poses here is that the matrix is symmetric; for example, the element in row
1, column 2 is equal to the element in row 2, column 1.
Suppose that we are working with ann-variate normal distribution. Our
matrix will havenrows andncolumns, and we wish each of thenvariables
to have variance 1, with correlationrhobetween pairs of variables. Forn=3
andrho = 0.2, for example, the desired matrix is as follows:


10. 20. 2


0. 210. 2


0. 20. 21




Here is code to generate this kind of matrix:

1 makecov <- function(rho,n) {
2 m <- matrix(nrow=n,ncol=n)
3 m <- ifelse(row(m) == col(m),1,rho)
4 return(m)
5 }


Let’s see how this works. First, as you probably guessed,col()returns
the column number of its argument, just asrow()does for the row num-
ber. Then the expressionrow(m)in line 3 returns a matrix of integer values,
each one showing the row number of the corresponding element ofm. For
instance,

>z
[,1] [,2]
[1,] 3 6
[2,] 4 7
[3,] 5 8
> row(z)
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3

Matrices and Arrays 69
Free download pdf