如何在 dplyr 函数的左侧执行 NSE?

How to perform NSE on the left hand side of a dplyr function?

考虑

library(dplyr)
assign_rhs <- function(df, rhs) {
  df %>%
    mutate(lhs = {{rhs}})
}

a = data.frame(b = 1, c = 2)

assign_rhs(a, b)

将产生:

  b c lhs
1 1 2   1

我也可以 assign_rhs(a, c)lhs 分配给 c 而不是 b.

如何才能让 lhs 也能接受 {rlang} 提供的 NSE {{}} 治疗?

我试过了

library(dplyr)
assign_lhs_rhs <- function(df, lhs, rhs) {
  df %>%
    mutate({{lhs}} = {{rhs}})
}

a = data.frame(b = 1, c = 2)

assign_lhs_rhs(lhs, b)

但是我在定义函数时出错

Error: unexpected '=' in:
"  df %>%
    mutate({{lhs}} ="

如果您使用 := 而不是 =,您可以在赋值的左侧使用 NSE:

assign_lhs_rhs <- function(df, lhs, rhs) {
    df %>%
        mutate({{lhs}} := {{rhs}})
}

a = data.frame(b = 1, c = 2)

assign_lhs_rhs(a, out, b)

输出:

  b c out
1 1 2   1

我不是非标准评估方面的专家,但据我所知,这样做的原因是无法覆盖 = 的工作方式,因此必须通过新运算符 :=.