Indexing Flashcards
What are the six ways of indexing values in R?
- Positive Integers
- Negative Integers
- Zero
- Blank Space
- Names
- Logical Values
What are the three basic indexing operators? What is each one used for?
- [] - used to return multiple items of an object. Returns an object with the same class as the original
- [[] ] - used to extract one element of a list or data frame. The object that is returned is not necessarily a list or data frame.
- $ - similiar to [[] ] , it’s used to extract a named element from a list or data frame.
How can I access values from indexes 1, 4 and 8 of the following vector?
cont = c(8, 4, NA, 9, 6, 1, 7, 9)
cont [c(1, 4, 8)]
What will this code return? Why?
cont = c(8, 4, NA, 9, 6, 1, 7, 9)
cont[-4]
8 4 NA 6 1 7 9
Because negative integer indexes return all values except for the one in the position specified after the negative sign, which in this case was 4.
What’s the return of this code?
cont = c(8, 4, NA, 9, 6, 1, 7, 9)
cont[-c(1, 4, 8)]
4 NA 6 1 7
What’s happening in this simple code?
cont[1:5]
We’re creating a sequence from 1 to 5 and using it to select elements of index 1 to 5 from object cont.
How can I select all elements that are not NA in vector v?
v[!is.na(v)]
How can I replace all NAs by 0 in my vector v?
v[is.na(v)] = 0
What is this code doing with my vector v?
is.na(v) = 3
It’s assigning NA to the 3rd element of vector v
What’s the difference between this two indexing codes on my vector v?
v[0]
v[]
v[0] - will return an empty vector (length 0). Rarely used.
v[] - will return all elements of the vector. Can be useful for matrices.
How can I easily assign letters (a,b,c …) as the names of my vector v elements?
names(v) = letters[1:length(v)]
How can I access that value that is in the third column and in the second row of my matrix mat?
mat[2, 3]
How can I access all values of the second column of my matrix mat? Why is that code valid?
mat[, 2]
This code is valid because blank space is also a valid way of indexing, meaning all values.
What is this code trying to attempt? What is a requirement for it to work?
mat[1, “C”]
It is trying to select the element of the first row and column C of matrix mat. The matrix must have named columns for it to work.
What’s are the outputs of this code? Why?
lis = list(c(3, 8, 7, 4), mat, 5:0)
class( lis[1] )
class( lis[[ 1] ] )
- *class( lis[1] )** returns “list”
- *class( lis[[ 1] ] )** returns “numeric”
This is because when I use operator [] I’m getting a subset of the original object, which is of the same class as the object, in this case list.
When I use operator [[] ] I return one element with it’s own class, which in this case is a numeric vector.