12.07.2015 Views

R dummies

R dummies

R dummies

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

constructing a matrix second.matrix that has four columns and three rows and thathas 1, 2, and 3 as values in the first, second, and third rows, respectively. Thefollowing command does so using the recycling of the first argument by the matrixfunction (see Chapter 4):> second.matrix first.matrix + second.matrix[,1] [,2] [,3] [,4][1,] 2 5 8 11[2,] 4 7 10 13[3,] 6 9 12 15This is the solution your math teacher would approve of if she asked you to dothe matrix addition of the first and second matrix. And even more, if thedimensions of both matrices are not the same, R will complain and refuse to carryout the operation, as shown in the following example:> first.matrix + second.matrix[,1:3]Error in first.matrix + second.matrix[, 1:3] : non-conformable arraysBut what would happen if instead of adding a matrix, we added a vector? Takea look at the outcome of the following code:> first.matrix + 1:3[,1] [,2] [,3] [,4][1,] 2 5 8 11[2,] 4 7 10 13[3,] 6 9 12 15Not only does R not complain about the dimensions, but it recycles the vectorover the values of the matrices. In fact, R treats the matrix as a vector in this caseby simply ignoring the dimensions. So, in this case, you don’t use matrix additionbut simple (vectorized) addition (see Chapter 4).By default, R fills matrices column-wise. Whenever R reads a matrix, it alsoreads it column-wise. This has important implications for the work withmatrices. If you don’t stay aware of this, R can bite you in the leg nastily.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!