4.3) Handling Dataframes: As Arrays
Indexing Arrays
Arrays are indexed in the same way as vectors, but with an index value for each dimension of the array. So a matrix (2-D array) might be indexed as Matrix[1,1:3]
to get the first row of the first three columns (rows first, then columns). Leaving one of the indices blank means that all the values are included (e.g. Matrix[,1]
to get the entire first column). If your rows and/or columns are named, you can also put the names (in inverted commas) in the square brackets. Now, a dataframe can be coerced to behave as a matrix for this purpose, so you can get rows and columns in all the same ways.
Select the first 10 rows of GRASS
. Then (revision from this page and the previous one) show five ways to extract the first column of GRASS
. What are the differences in output?
Create a matrix as follows: Matrix <- matrix(c(1:16),nrow=4,ncol=4)
. How could you extract a diagonal? It should be obvious that the answer is not Matrix[1:4,1:4]
(try it!). The diagonal is a vector of numbers, but it's not a 2-D subset of the matrix, so in this case we can't simply use a set of square brackets. Fortunately there is a function diag()
for matrices, but if you needed to compile a vector from a matrix using some other set of coordinates, it's more complicated - one way would be to use a for()
loop.