在 dplyr 中取消引用 mutate 函数右侧的变量名 [英] Unquote the variable name on the right side of mutate function in dplyr

查看:19
本文介绍了在 dplyr 中取消引用 mutate 函数右侧的变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 dplyr 和函数创建一个用于创建滞后变量的函数.但是,问题是我找不到如何在 mutate 函数的右侧取消引用变量名.

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 right side of mutate function.

mutate(dt,
    !!varname_t1 := !!varname_t0 # it does not work. 
)

下面是我的真实例子.

A.这是示例数据.

df <- tibble(
  a = sample(5)
)

# A tibble: 5 x 1
      a
  <int>
1     3
2     5
3     4
4     1
5     2

我想把数据做成这样.

df <- df %>% mutate(a2 = lag(a1))

# A tibble: 5 x 2
     a1    a2
  <int> <int>
1     3    NA
2     1     3
3     5     1
4     2     5
5     4     2

B.我创建了一个函数,但它不起作用.我认为问题是这条线.在右侧,我不知道如何取消引用.

B. I created a function but it does not work. I think the problem is this line. On the right side, I do not know how to unquote.

!!varname_t1 := !!varname_t0

我的功能是这样的.

lag1_mutate <- function(dt, varname, time) { # time here is "after"

    # enquo 
    varname <- enquo(varname) 
    time1 <- enquo(time) 
    time0 <- time-1; time0 <- enquo(time0)

    # create the name of variables
    varname_t0 <- paste0(quo_name(varname), quo_name(time0)) 
    varname_t1 <- paste0(quo_name(varname), quo_name(time1))

    # check 
    print(varname_t0)
    print(varname_t1)

    # mutate        
    mutate(dt, 
        !!varname_t1 := !!varname_t0 # <-- problem, here
        # !!varname_t1 := lag(!!varname_t0) # produced only NAs
    )
}

实际结果是这样的.

lag1_mutate(df, a, 2)

[1] "a1"
[1] "a2"
# A tibble: 5 x 2
      a    a2
  <int> <chr>
1     4    a1
2     1    a1
3     3    a1
4     2    a1
5     5    a1

推荐答案

我认为您必须将 RHS 字符串转换为 quosure,您可以使用 rlang<中的 sym/代码> 包.所以用

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)))

那么你的函数就会产生

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

(你没有设置种子,所以我的tibble值和你的不同.)

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

这篇关于在 dplyr 中取消引用 mutate 函数右侧的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆