How to Use Dollar($) Sign in R

In R, the dollar sign ($) is used to access elements (columns) of a list or a data frame by name.

You can also use the $ operator to add, update, and delete variables from the list and data frame columns.

This operator is somewhat limited in programmability. For example, you can’t easily use a variable to specify a column name when using $. In such cases, alternative methods like “[[“ or “[“ are more appropriate.

Example 1: Accessing the element of a list by name

Figure of Accessing the element of a list by name using the $ sign

Figure: Usage of $ sign

list_a <- list("PS5" = "Miles Morales", "Xbox" = "Halo Infinite")

list_a$PS5

Output

[1] "Miles Morales"

Example 2: Adding a new variable to a list

Figure of adding a new element to a list using $ sign in R

Figure: Usage of a dollar sign to add a new variable to a list

list_a <- list("PS5" = "Miles Morales", "Xbox" = "Halo Infinite")
print(list_)

print("After adding a variable to a list")

list_a$Nintendo <- "Legend of Zelda"
print(list_a)

Output

$PS5
[1] "Miles Morales"

$Xbox
[1] "Halo Infinite"

[1] "After adding a variable to a list"

$PS5
[1] "Miles Morales"

$Xbox
[1] "Halo Infinite"

$Nintendo
[1] "Legend of Zelda"

Example 3: Removing an element from the list

To delete the variable or name from the list, you can “NULL” to the name.

Figure of deleting an Element from List using $ sign

Figure: Deleting an element from a list using the $ sign

list_a <- list("PS5" = "Miles Morales", "Xbox" = "Halo Infinite")

list_a$PS5 <- NULL

list_a

Output

$Xbox
[1] "Halo Infinite"

Example 4: Adding a column to the data frame

Visualization of adding a column to the data frame using the $ sign

Figure: Adding a column to the data frame using $ sign

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

df$col4 <- c(10, 11, 12)

print(df)

Output

Output of Adding a column to the data frame using the $ sign

Example 5: Accessing the column of the data frame

Figure of accessing the column of the data frame using the $ sign

Figure: Accessing a column values using $ sign

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

print(df$col2)

Output

[1] 4 5 6

Example 6: Deleting the column of the data frame

Figure of Deleting the column of the data frame using the $ sign

Figure: Deleting a column of a data frame using $ sign

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

df$col2 <- NULL
print(df)

Output

Output of Delete the column of data frame using the $ sign

That’s it.

Leave a Comment