<- 2
x x
[1] 2
1] x[
[1] 2
Marie-Hélène Burle
This section covers indexing from the various data structures.
Here is an example with an atomic vector of size one:
Indexing in R starts at 1
and is done with square brackets next to the element to index:
What happens if we index out of range?
Example for an atomic vector with multiple elements:
Indexing also allows to modify some of the values of mutable objects:
Not all languages behave the same when you assign the same mutable object to several variables, then modify one of them.
Don’t try to run this code in R. This is for information only.
[1, 2, 3]
[4, 2, 3]
[4, 2, 3]
Modifying a
also modifies b
: this is because no copy is made when you modify a
. If you want to keep b
unchanged, you need to assign an explicit copy of a
to it with b = copy.copy(a)
.
Here, the default is to create a new copy in memory when a
is transformed so that b
remains unchanged.
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[1] 8
, , 1
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
, , 2
[,1] [,2]
[1,] 7 10
[2,] 8 11
[3,] 9 12
, , 3
[,1] [,2]
[1,] 13 16
[2,] 14 17
[3,] 15 18
, , 4
[,1] [,2]
[1,] 19 22
[2,] 20 23
[3,] 21 24
[1] 14
[[1]]
[1] 2
[[2]]
[1] 3 4 5 6 7 8
[[3]]
[1] 2 1
[[4]]
[1] FALSE
[[5]]
[1] "string"
Indexing a list returns a list:
To extract elements of a list, double square brackets are required:
Your turn:
Try to extract the number 7
from this list.
country var
1 Canada 2.9
2 USA 3.1
3 Mexico 4.5
Indexing dataframes can be done by using indices, as we saw for matrices:
It can also be done using column names thanks to the $
symbol (a column is a vector, so indexing from a column is the same as indexing from a vector):
A data frame is actually a list of vectors representing the various columns:
Indexing a column can thus also be done by indexing the element of the list with double square brackets (although this is a slower method).
We get the same result with: