我认为通过之前的问题,我已经解决了在 tidyverse 中使用变量的所有问题。但我刚刚使用我不明白的 mutate 函数遇到了一个问题。下面是一个将 dplyr 语句通过管道传输到 ggplot 的玩具示例。
我添加了一个显式的变异步骤mutate(mpg = mpg * 10) %>%,效果很好。
.data[[]]另外,在语句的 RHS 上按名称添加列也可以使用 来正常工作mutate(mpg = .data[[x_value]] * 10) %>%。
然而,当我在方程的 LHS 上使用变量时,我.data[[]]得到:!!sym()mutate(.data[[x_value]] = mpg * 10) %>%
Error: unexpected '=' in:
"data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(.data[[x_value]] ="
Run Code Online (Sandbox Code Playgroud)
显而易见的问题是:为什么这不起作用?显而易见的后续问题是:如何使用变量来指定要变异的列?
作为参考,工作示例:
Error: unexpected '=' in:
"data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(.data[[x_value]] ="
Run Code Online (Sandbox Code Playgroud)

#// library
library(tidyverse)
data <- mtcars
data$carb <- as.factor(data$carb)
remove_col <- "carb"
remove_val <- 4
x_value <- "mpg"
y_value <- "drat"
#// explicit mutate condition
data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(mpg = mpg * 10) %>%
ggplot() + geom_point(aes(x = .data[[x_value]], y = .data[[y_value]], color = .data[[remove_col]] )) +
ggtitle("Variables for `geom_point` and `filter`")
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2021 年 1 月 13 日创建(v0.3.0)
根据 LHS 或 RHS 上是否有变量,处理方式有所不同。如果 LHS 上有变量,则使用!!variable_name := ....wherevariable_name应该是字符串值。
library(dplyr)
library(ggplot2)
data <- mtcars
data$carb <- as.factor(data$carb)
remove_col <- "carb"
remove_val <- 4
x_value <- "mpg"
y_value <- "drat"
data %>%
filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(!!x_value := .data[[x_value]] * 10) %>%
ggplot() + geom_point(aes(x = .data[[x_value]],
y = .data[[y_value]],
color = .data[[remove_col]] )) +
ggtitle("Variables for `geom_point` and `filter`")
Run Code Online (Sandbox Code Playgroud)