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 <- list(a = 1, b = 2, c = 3)
Then we can access any of the elements of the list by its name. For example, to extract element a, we will use $ operator as follows.
my_list$a ## 1
Let us consider another example, where the elements of our list are vectors. In the list below, we have numeric vector called “x” and a character vector called “y”:
my_list <- list(x = c(1, 2, 3), y = c("a", "b", "c"))
To get the “x” element from this list, we can use the $ operator like this:
# extract element x from list using $ operator my_list$x
And we would the vector in element “x”
## c(1,2,3)
Extracting elements from a data frame using $ operator in R
Suppose we have a data frame called “df” that contains three columns, including a column called “col2”.
df = data.frame(col1 = c(1,2,3), col2 = c(1,4,9), col3 = c(1,8,27)) > df col1 col2 col3 1 1 1 1 2 2 4 8 3 3 9 27
To 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 9
The $ 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] # 8
To 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.