I am trying to create a function to create a lagging variable using dplyr and a function. But the problem is that I cannot find how to unquote the variable name on the right side of the mutate function.
mutate(dt,
!!varname_t1 := !!varname_t0
)
Below is a real example.
and. Here is sample data.
df <- tibble(
a = sample(5)
)
a
<int>
1 3
2 5
3 4
4 1
5 2
I want to make such data.
df <- df %>% mutate(a2 = lag(a1))
a1 a2
<int> <int>
1 3 NA
2 1 3
3 5 1
4 2 5
5 4 2
Q. I created a function, but it does not work. I think the problem is in this line. On the right side, I do not know how unconditionally.
!!varname_t1 := !!varname_t0
My function is like that.
lag1_mutate <- function(dt, varname, time) {
varname <- enquo(varname)
time1 <- enquo(time)
time0 <- time-1; time0 <- enquo(time0)
varname_t0 <- paste0(quo_name(varname), quo_name(time0))
varname_t1 <- paste0(quo_name(varname), quo_name(time1))
print(varname_t0)
print(varname_t1)
mutate(dt,
!!varname_t1 := !!varname_t0
)
}
The actual result is this.
lag1_mutate(df, a, 2)
[1] "a1"
[1] "a2"
a a2
<int> <chr>
1 4 a1
2 1 a1
3 3 a1
4 2 a1
5 5 a1
source
share