Dollar Sign ($) in R

The dollar ($) operator is one of the exaction operators in R. It allows you to extract, assign and add elements or columns to a list or a data frame. This guide explains using the dollar sign ($) in R.

Syntax

The following syntax will help you understand how to use the $ operator in R:

Object$NamedElement

Arguments

  • Object = any R object like a list or a data frame.
  • NamedElement = element of a list or a column of a data frame.

Example 1: Extract an element from a list

#creating a list
my_list <- list(x=10, y=20, z=30)
#extracting the element from the list
my_list$z

Output

[1] 30

In the above example, we extracted the element z’s value from the list using the $ operator.

Example 2: Extract a column from a data frame

#creating a data frame
heroes <- data.frame(Hero_Name=c('Batman','Flash','Superman','Green Arrow'),
Real_Name=c('Bruce Wayne', 'Barry Allen', 'Clark Kent', 'Oliver Queen'),
Powers=c('Money','Speed','Strength','Archery'))
#extracting column Real_Name
heroes$Real_Name

Output

[1] "Bruce Wayne" "Barry Allen" "Clark Kent" "Oliver Queen"

We extracted the column Real_Name from the data frame in the above example using the $ operator.

Example 3: Assigning a new value to an element in a list

#creating a list
my_list <- list(x=10, y=20, z=30)
#assigning a new value to y
my_list$y <- 25
my_list

Output

$x
[1] 10
$y
[1] 25
$z
[1] 30

In the above example, we changed the value of element y from 20 to 25 using the $ operator.

Example 4: Changing a column value in a data frame

#creating a data frame
heroes <- data.frame(Hero_Name=c('Batman','Flash','Superman','Green Arrow'),
Real_Name=c('Bruce Wayne', 'Barry Allen', 'Clark Kent', 'Oliver Queen'),
Powers=c('Money','Speed','Strength','Archery'))
#changing the value Money in the column Powers
heroes$Powers <- c('Martial Arts','Speed','Strength','Archery')
heroes$Powers

Output

[1] "Martial Arts" "Speed" "Strength" "Archery"

In the above example, we changed the value Money to Martial Arts in the column Powers.

Example 5: Adding a new element to a list

#creating a list
my_list <- list(x=10, y=20, z=30)
#adding a new value
my_list$a <- 40
my_list

Output

$x
[1] 10
$y
[1] 20
$z
[1] 30
$a
[1] 40

In the above example, we added a new element w, with a value of 40, to the list.

Example 6: Adding a new column to a data frame

#creating a data frame
heroes <- data.frame(Hero_Name=c('Batman','Flash','Superman','Green Arrow'),
Real_Name=c('Bruce Wayne', 'Barry Allen', 'Clark Kent', 'Oliver Queen'),
Powers=c('Money','Speed','Strength','Archery'))
#adding a new column named Rank
heroes$Rank <- c(2,3,1,4)
heroes

Output

New Column
Added a new column named “Rank” to the data frame.

In the above example, we added a new column, Rank, with the values to the data frame.

Leave a Comment