【问题标题】:Unquote the variable name on the right side of mutate function in dplyr取消引用 dplyr 中 mutate 函数右侧的变量名
【发布时间】:2017-09-09 14:45:03
【问题描述】:

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

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.我创建了一个函数,但它不起作用。我认为问题在于这条线。在右侧,我不知道如何取消引用。

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

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我认为您必须将 RHS 字符串转换为 quosure,您可以使用 rlang 包中的 sym 来完成此操作。所以使用

    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 值与你的不同。)

    【讨论】:

    • 谢谢!根据您的回答,我在下面创建了循环以创建从 2 到 10 的滞后变量。但是,它不起作用。它只生成一个“ai”变量而不是“a2”变量并给出错误。 for(i in c(2:10)) { df
    • 这工作lag1_mutate &lt;- function(dt, varname, time) { varname_t0 &lt;- paste0(substitute(varname), time-1); varname_t1 &lt;- paste0(substitute(varname), time); mutate(dt, !!varname_t1 := lag(!!rlang::sym(varname_t0))) } @aasungh
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 2021-08-25
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多