Matrices can be created in R in a variety of ways. Perhaps the simplest is to create the columns and then glue them together with the command cbind. For example,
> x<-c(5,7,9)
> y<-c(6,3,4)
> z<-cbind(x,y)
> z
x y
[1,] 5 6 [2,] 7 3 [3,] 9 4The dimension of a matrix can be checked with the dim command:
> dim(z)
[1] 3 2i.e., three rows and two columns. There is a similar command, rbind, for building matrices by gluing rows together. The functions cbind and rbind can also be applied to matrices themselves (provided the dimensions match) to form larger matrices. For example,
> rbind(z,z)
[,1] [,2] [1,] 5 6 [2,] 7 3 [3,] 9 4 [4,] 5 6 [5,] 7 3 [6,] 9 4Matrices can also be built by explicit construction via the function matrix. For example, z<-matrix(c(5,7,9,6,3,4),nrow=3)
results in a matrix z identical to z above. Notice that the dimension of the matrix is determined by the size of the vector and the requirement that the number of rows is 3, as specified by the argument nrow=3. As an alternative we could have specified the number of columns with the argument ncol=2(obviously, it is unnecessary to give both). Notice that the matrix is ‘filled up’ column-wise. If instead you wish to fill up row-wise, add the option byrow=T. For example,
> z<-matrix(c(5,7,9,6,3,4),nr=3,byrow=T)
> z
[,1] [,2] [1,] 5 7 [2,] 9 6 [3,] 3 4Notice that the argument nrow has been abbreviated to nr. Such abbreviations are always possible for function arguments provided it induces no ambiguity – if in doubt always use the full argument name. As usual, R will try to interpret operations on matrices in a natural way. For example, with z as above, and
> y<-matrix(c(1,3,0,9,5,-1),nrow=3,byrow=T)
> y
[,1] [,2] [1,] 1 3 [2,] 0 9 [3,] 5 -1we obtain
> y+z
[,1] [,2] [1,] 6 10 [2,] 9 15 [3,] 8 3and
> y*z
[,1] [,2] [1,] 5 21 [2,] 0 54 [3,] 15 -4Notice, multiplication here is component-wise rather than conventional matrix multiplication. Indeed, conventional matrix multiplication is undefined for y and z as the dimensions fail to match. Let’s now define
> x<-matrix(c(3,4,-2,6),nrow=2,byrow=T)
> x
[,1] [,2] [1,] 3 4 [2,] -2 6Matrix multiplication is expressed using notation %*%:
> y%*%x
[,1] [,2] [1,] -3 22 [2,] -18 54 [3,] 17 14Other useful functions on matrices are t to calculate a matrix transpose and solve to calculate inverses:
> t(z)
[,1] [,2] [,3] [1,] 5 9 3 [2,] 7 6 4and
> solve(x)
[,1] [,2] [1,] 0.23076923 -0.1538462 [2,] 0.07692308 0.1153846As with vectors it is useful to be able to extract sub-components of matrices. In this case, we may wish to pick out individual elements, rows or columns. As before, the[ ]notation is used to subscript. The following examples should make things clear:
> z[1,1] [1] 5
> z[c(2,3),2] [1] 6 4
> z[,2] [1] 7 6 4
> z[1:2,] [,1] [,2] [1,] 5 7
[2,] 9 6So, in particular, it is necessary to specify which rows and columns are required, whilst omitting the integer for either dimension implies that every element in that dimension is selected.