Tidy Evaluation: {{ }} and .data
Write dplyr functions that accept column names as arguments safely.
The Problem: Programming with dplyr
dplyr uses non-standard evaluation (NSE) — column names are passed unquoted. This is convenient interactively but tricky when writing functions. How do you pass a column name as a variable to a dplyr function?
library(dplyr)
df <- data.frame(x=1:5, y=c(2,4,6,8,10))
# Works fine interactively:
df %>% summarize(mean_x = mean(x))
# But what if 'x' is a variable?
col_name <- 'x'
# df %>% summarize(result = mean(col_name)) # WRONG! treats 'col_name' as column
cat('Need tidy evaluation to solve this!')The {{ }} Embrace Operator
Inside a function, use {{ col_var }} (called 'curly-curly' or 'embrace') to pass a column name that will be evaluated in the data frame context. This is the recommended approach for most dplyr function programming.
library(dplyr)
df <- data.frame(
group = c('A','A','B','B'),
sales = c(100, 120, 200, 180),
costs = c(60, 70, 110, 90)
)
# Function using {{ }}
group_mean <- function(data, group_col, value_col) {
data %>%
group_by({{ group_col }}) %>%
summarize(mean_val = mean({{ value_col }}), .groups = 'drop')
}
group_mean(df, group, sales)
group_mean(df, group, costs)All lessons in this course
- Grouped Summaries and group_by()
- Window Functions: lag, lead, cumsum
- Multi-table Joins in dplyr
- Tidy Evaluation: {{ }} and .data