Subscripts and Indices
While we typically aim to apply functions to vectors as a whole, there are circumstances where we want to select only some of the elements of a vector. This selection is done using subscripts (also known as indices). Subscripts have square brackets [2] while functions have round brackets (2). Subscripts on vectors, matrices, arrays and dataframes have one set of square brackets [6], [3,4] or [2,3,2,1] while subscripts on lists have double square brackets [[2]] or [[i,j]] (see p. 65). When there are two subscripts to an object like a matrix or a dataframe, the first subscript refers to the row number (the rows are defined as margin no. 1) and the second subscript refers to the column number (the columns are margin no. 2). There is an important and powerful convention in R such that when a subscript appears as a blank it is understood to mean ‘all of’. Thus
- [,4] means all rows in column 4 of an object
- [2,] means all columns in row 2 of an object.
There is another indexing convention in R which is used to extract named components from objects using the $ operator like this: model$coef or model$resid (p. 363). This is known as ‘indexing tagged lists’ using the element names operator $.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access