I haven't used meta-programming operators in R for a while, and I came across this today. What is the recommended way to add a new column?
# Using embrace operator
add_col1 <- function(data, col_name){
out <- data |>
dplyr::mutate({{ col_name }} := "new")
return(out)
}
# Use
add_col2 <- function(data, col_name){
out <- data |>
dplyr::mutate(!!col_name := "new")
return(out)
}
x1 <- add_col1(cars, "new_col")
x2 <- add_col2(cars, "new_col")
all.equal(x1, x2)
add_col1(cars, new_col)
# Fails due to missing enquo() call
add_col2(cars, new_col)
What is the recommended way to write such dplyr-type function? From reading some of the docs, I found that using enquo() for normal usage is no longer recommended, which is why add_col2 fails without quotes here.
The only semantic advantage I can see to using add_col2 is that it enforces the use of quotes with col_name, which kinda suggests that the column does not yet exist. However, this is a very weak argument.