Monday, January 20, 2025
HomeProgrammingDplyr - What Does the !! Operator Mean in R, Particularly In

Dplyr – What Does the !! Operator Mean in R, Particularly In

In R’s dplyr package, the !! operator is used for unquoting, allowing you to evaluate expressions within functions that use non-standard evaluation (NSE). This is particularly useful when you want to programmatically refer to column names or expressions.

For example, if you have a variable nm containing a column name as a string, you can use rlang::sym() to convert it to a symbol and then unquote it with !! within a mutate() function:

r
library(dplyr)
library(rlang)

nm <- "Sepal.Width"
x <- sym(nm)

iris %>%
mutate(!!x := !!x * 2)

In this code, !!x unquotes the symbol x, allowing mutate() to interpret it as the column Sepal.Width and create a new column with its values doubled.

Unquoting is essential in dplyr when you need to programmatically refer to variables or column names within functions that rely on NSE. It enables dynamic evaluation of expressions, making your code more flexible and expressive.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x