Table of Contents
The dollar sign ($) operator in R is used to extract elements from an object such as a list or data frame, allowing you to select a single element or multiple elements from the object. The dollar sign ($) operator works in combination with the name of the element or elements you want to extract. For example, if you want to extract the element “x” from the list “mylist”, you can use the command mylist$x. You can also use the dollar sign ($) operator to access components of list elements. For example, if you have a list containing vectors, you can use the command mylist$x[1] to access the first element of the vector “x”.
You can use the dollar sign operator ($) in R to create and access variables in lists and data frames.
The following examples shows four common way to use this operator in practice.
Example 1: Use Dollar Sign to Create Variable in List
Suppose we create the following list in R:
#create list
my_list <- list(A= c('X', 'Y', 'Z'),
B=20,
C=1:5)
#view list
my_list
$A
[1] "X" "Y" "Z"
$B
[1] 20
$C
[1] 1 2 3 4 5
We can use the dollar sign operator ($) to create a new variable in this list:
#create new variable in list
my_list$D <- c('Hey', 'Hi', 'Hello')
#view updated list
my_list
$A
[1] "X" "Y" "Z"
$B
[1] 20
$C
[1] 1 2 3 4 5
$D
[1] "Hey" "Hi" "Hello"
Notice that the new variable D has been added to the list.
Example 2: Use Dollar Sign to Access Variable in List
We can also use the dollar sign operator ($) to access a specific variable in a list.
For example, we can use the following code to access the variable C in the list:
#create list
my_list <- list(A= c('X', 'Y', 'Z'),
B=20,
C=1:5)
#access variable C
my_list$C
[1] 1 2 3 4 5
Notice that only the values for variable C are returned.
Example 3: Use Dollar Sign to Create Variable in Data Frame
Suppose we create the following data frame in R:
#create data frame
df <- data.frame(team=c('Mavs', 'Spurs', 'Rockets', 'Nets'),
points=c(140, 115, 109, 98))
#view data frame
df
team points
1 Mavs 140
2 Spurs 115
3 Rockets 109
4 Nets 98
We can use the dollar sign operator ($) to create a new variable in the data frame called assists:
#create new variable called assists
df$assists <- c(20, 25, 29, 49)
#view updated data frame
df
team points assists
1 Mavs 140 20
2 Spurs 115 25
3 Rockets 109 29
4 Nets 98 49
Notice that the new variable assists has been added to the data frame.
Example 4: Use Dollar Sign to Access Variable in Data Frame
We can also use the dollar sign operator ($) to access a specific variable in a data frame.
For example, we can use the following code to access the points variable in the data frame:
#create data frame
df <- data.frame(team=c('Mavs', 'Spurs', 'Rockets', 'Nets'),
points=c(140, 115, 109, 98))
#access values for points
df$points
[1] 140 115 109 98
Notice that only the values for the points variable are returned.
The following tutorials explain how to use other common functions in R: