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 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 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 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 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 #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 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.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use the View() Function in R
How to Use the aggregate() Function in R
How to Use the replace() Function in R