17.3 Functions with unquoted arguments
Code
library(tidyverse)
df <- tibble(
a = sample(5),
b = sample(5)
)
lag1_mutate <- function(dt, varname, time) {
varname_t0 <- paste0(substitute(varname));
varname_t1 <- paste0(substitute(varname), time);
dplyr::mutate(dt, !!varname_t1 := lag(!!rlang::sym(varname_t0)))
}
lag1_mutate(df, a, 2)
lag1_mutate(df, b, 3)
# A tibble: 5 × 3
a b a2
<int> <int> <int>
1 1 3 NA
2 5 5 1
3 2 4 5
4 4 2 2
5 3 1 4
# A tibble: 5 × 3
a b b3
<int> <int> <int>
1 1 3 NA
2 5 5 3
3 2 4 5
4 4 2 4
5 3 1 2
Adapted from here: https://stackoverflow.com/questions/46131829/unquote-the-variable-name-on-the-right-side-of-mutate-function-in-dplyr