# Make a 3-element list
<- list("a" = 1:3, "b" = "hello", "c" = 7:9) my_list
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.
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
1] my_list[
$a
[1] 1 2 3
Using either element position or element name (if there is one) is supported.
# Select with name
"c"] 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[[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.
1]] my_list[[
[1] 1 2 3
Again, both element position and element name (if there is one) are supported.
"c"]] my_list[[
[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.
$a my_list
[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
<- list("d" = 4, "e" = 5, "f" = 6)
my_list2
# Make an object containing the name we want
<- "e"
wanted_bit
# 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
$wanted_bit my_list2
- 2
-
This returns
NULL
because"wanted_bit"
is not the name of any element of this list.
NULL