R Basic

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of a list or a data frame by their name. It also works with your environment. For example, it can fetch you the current environment variables. With its help, you can add, modify, or delete variables from the list and data frame columns.

It is a shorthand for accessing elements without using square brackets ([[]] or []) or other subsetting functions.

Syntax

object$name

In the above syntax, there are two components:

Argument Description
object It represents the R object that contains named components.
name It defines the name of the element to extract or assign.

For assignment

object$name <- value
Argument Description
value It declares the value that needs to be assigned to the named component.

Accessing the element of a list by name

The $ operator requires the exact name of the component and is case-sensitive. It does not support partial matching by default unless options(check.names = FALSE) is set, which is rare.

Figure: Usage of $ sign

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

list_a$PS5

# Output: [1] "Miles Morales"

The above output shows that it extracted and returned a single component in its native type.

Adding a new variable to a list

Let’s add a named element to the list. This helps create a dynamic list you can add to or modify.

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"

Removing an element from the list

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

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

list_a$PS5 <- NULL

list_a

# Output:
# $Xbox
# [1] "Halo Infinite"

Adding a column to the data frame

Data Frames are list-like objects where each column is a named component. That’s why you can use the $ sign on it.

Add a new column “col4” to the existing data frame by assigning a new column name to a data frame using $ and assigning the values using the <- operator.

 

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)

In the above output figure, we specifically mentioned using a red-bordered rectangle to indicate that a new column has been added to an existing data frame. You can also update an existing column with new values.

Accessing the column of the data frame

Since each column is named list, you can retrieve a specific element (value) from a named list (column of the data frame).

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

Deleting the column of the data frame

If you assign NULL to a specific column, it will be removed from the data frame because it now has no value and does not add anything new.

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

df$col2 <- NULL
print(df)

Accessing objects in an environment

If you have defined your custom environment, the $ sign will help you retrieve the environment variable.

# Creating an environment
env <- new.env()
env$var <- 21

# Accessing 'var'
value <- env$var

print(value)

# Output: [1] 21

It helps manage the global state of our application.

Using $ with Packages

R provides many built-in packages; you can choose one and access a function or dataset from a loaded package.

# Access a dataset from the 'datasets' package

head(datasets::mtcars$mpg)

# Output: [1] 21.0 21.0 22.8 21.4 18.7 18.1

In the above code, the datasets::mtcars$mpg uses $ to access the mpg column from the mtcars dataset.

Limitations: Dynamic Names

The $ 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.

The $ does not evaluate variables as names, requiring [[ for dynamic access. This is a key limitation when column names are stored in variables for the $ operator.

Non-Existent Names

If you attempt to access a non-existent element in the list, it will return NULL.

If you attempt to access a non-existent column in the data frame, it will also return NULL.

Here is the code:

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

print(list_a$PS4)

# Output: NULL


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

print(df$col4)

# Output: NULL

That’s it.

Recent Posts

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only…

2 weeks ago

Printing an Output of a Program in R

When working with R in an interactive mode, you don't need to use any functions…

2 weeks ago

How to Calculate Variance in R

To calculate the sample variance (measurement of spreading) in R, you should use the built-in…

3 weeks ago

tryCatch() Function in R

The tryCatch() function acts as a mechanism for handling errors and other conditions (like warnings…

4 weeks ago

R grep(): Finding a Position of Matched Pattern

The grep() function in R  searches for matches to a pattern within a character vector.…

4 weeks ago

How to Check If File and Folder Already Exists in R

Whether you are reading or writing files via programs in the file system, it is…

1 month ago