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.

id first.matrix[-id][1] 1 2 3 4 5 6 7 9 10 11 12This returns a vector, because the 11 remaining elements don’t fit into amatrix anymore. Now what happened here exactly? Remember that matrices areread column-wise. To get the second element in the third column, you need to dothe following:1. Count the number of rows, using nrow(), and store that in avariable — for example nr.You don’t have to do this, but it makes the code easier to read.2. Count two columns and then add 2 to get the second element inthe third column.Again store this result in a variable (for example, id).3. Use the one-dimensional vector extraction [] to drop this value, asshown in Chapter 4.You can do this in one line, like this:> first.matrix[-(2 * nrow(first.matrix) + 2)][1] 1 2 3 4 5 6 7 9 10 11 12This is just one example of how you can work with indices while treating amatrix like a vector. It requires a bit of thinking at first, but tricks like these canoffer very neat solutions to more complex problems as well, especially if you needyour code to run as fast as possible.Juggling dimensionsAs with vectors, you can combine multiple numbers in the indices. If you wantto drop the first and third rows of the matrix, you can do so like this:> first.matrix[-c(1, 3), ][1] 2 5 8 11Wait a minute. . . . There’s only one index. R doesn’t return a matrix here — itreturns a vector!

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

Saved successfully!

Ooh no, something went wrong!