How to use dollar $ operator in R
R programming language uses $ operator (dollar operator) for extracting or accessing elements from data structures like list or dataframe. For example, with $ operator we can select specific elements of a list or dataframe by their names instead of their position.
In this post, we will learn two most common uses of $ operator in with examples.
Extracting elements from a list using $ operator in R
Suppose we have a list called “my_list” that contains three named elements as shown below.
# extract element a from list using $ operator
my_list df
col1 col2 col3
1 1 1 1
2 2 4 8
3 3 9 27To extract the “col3” column from this data frame, we can use the $ operator like this. And we will get the column as a vector.
df$col2
[1] 1 4 9The $ operator in R can also be used in combination with the square bracket notation to extract elements. For example, to extract the second element from the third column of the data frame above, we could use the following code:
df$col3[2]
# 8To summarize, although it looks mysterious at first, the $ operator is a convenient and easy-to-use tool for extracting elements from lists and data frames by name in base R.