We often wish to examine part of a set of data. Suppose that our data is
stored in the matrix A
.
> A = matrix(1:16, 4, 4)
> A
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
Then, typing
> A[2, 3]
[1] 10
will select the element corresponding to the second row and the third column.
The first number after the open-bracket symbol [
always refers to
the row, and the second number always refers to the column. We can also
select multiple rows and columns at a time, by providing vectors as the
indices.
Note: In R indexing starts at 1, meaning the first element of a vector, matrix or any kind of data structure is at index 1. Most of the other languages such as Python or Java start indexing at 0
> A[c(1, 3), c(2, 4)]
[,1] [,2]
[1,] 5 13
[2,] 7 15
> A[1:3, 2:4]
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
> A[1:2,]
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
> A[, 1:2]
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
The last two examples include either no index for the columns or no index for the rows. These indicate that R should include all columns or all rows, respectively. R treats a single row or column of a matrix as a vector.
> A[1,]
[1] 1 5 9 13
The use of a negative sign -
in the index tells R to keep all rows or columns
except those indicated in the index.
> A[-c(1, 3),]
[,1] [,2] [,3] [,4]
[1,] 2 6 10 14
[2,] 4 8 12 16
> A[-c(1, 3), -c(1, 3, 4)]
[1] 6 8
A
and store it in A1
A2
A3
A4
+
operator and store it in A5
Use the code below as a starting point.