Unquote the variable name on the right side of mutate function in dplyr

后端 未结 1 1086
猫巷女王i
猫巷女王i 2020-12-15 12:41

I am trying to make a function for a creating lagged variable using dplyr and function. But, the problem is that I cannot find how to unquote the variable name on the ri

相关标签:
1条回答
  • 2020-12-15 13:03

    I think you have to convert the RHS string to a quosure, which you can do with sym from the rlang package. So use

    mutate(dt, !!varname_t1 := lag(!!rlang::sym(varname_t0)))
    

    Then your function will yield

    lag1_mutate(df, a, 1)
    # [1] "a0"
    # [1] "a1"
    # # A tibble: 5 x 2
    #      a0    a1
    #   <int> <int>
    # 1     3    NA
    # 2     4     3
    # 3     1     4
    # 4     5     1
    # 5     2     5
    

    (You set no seed, so my tibble values are different from yours.)

    0 讨论(0)
提交回复
热议问题