Selecting Elements (in R)

[, [[, and $

In R, there are three primary methods of selecting elements in an object – [, [[, and $. However, many R users don’t actually know how the three methods differ from one another. The following attempts to clarify this! Let’s start with a multi-element list and then check out an example of each.

# Make a 3-element list
my_list <- list("a" = 1:3, "b" = "hello", "c" = 7:9)

If x is a train with multiple cars where each car may contain some number of items, x[1] grabs the whole first train car. This means that the extracted bit is still the same type of data as the original object; in this case that means we still have a list, just this time it has only a single element.

# Select with position
my_list[1]
$a
[1] 1 2 3

Using either element position or element name (if there is one) is supported.

# Select with name
my_list["c"]
$c
[1] 7 8 9

If x is a train with multiple cars where each car may contain some number of items, x[[1]] grabs the contents of the whole first train car. This means that the type of data changes to whatever is stored in that element. In this case that means we now have a vector.

my_list[[1]]
[1] 1 2 3

Again, both element position and element name (if there is one) are supported.

my_list[["c"]]
[1] 7 8 9

If x is a train with multiple cars where each car may contain some number of items, x$name also grabs the contents of the whole first train car. x$name is shorthand for x[["name"]]! However, only the element name is supported when using this method for selecting an element.

my_list$a
[1] 1 2 3

[[ versus $

The above examples show how [[ and $ function similarly but there is an important caveat to this! If name is an object containing one of the names in x, then the two methods differ. x[[name]] will get the entity that matches the value of name while x$name will get an entity that is itself named name. See an example below:

# Make a new list
my_list2 <- list("d" = 4, "e" = 5, "f" = 6)

# Make an object containing the name we want
wanted_bit <- "e"

# Select it with double brackets
my_list2[[wanted_bit]]
1
wanted_bit is interpreted as "e" because that is the value bound to that object.
[1] 5
# Select it with a dollar sign
my_list2$wanted_bit
2
This returns NULL because "wanted_bit" is not the name of any element of this list.
NULL