【发布时间】:2021-01-14 03:10:36
【问题描述】:
我认为我的previous questions 已经解决了在 tidyverse 中使用变量的所有问题。但是我只是在使用我不理解的 mutate 函数时遇到了问题。下面是一个将 dplyr 语句导入 ggplot 的玩具示例。
我添加了一个显式的变异步骤mutate(mpg = mpg * 10) %>%,效果很好。
还可以使用mutate(mpg = .data[[x_value]] * 10) %>% 在语句的右轴上按名称添加.data[[]] 的列。
但是,当我在方程的 LHS 上使用 .data[[]] 或 !!sym() 上的变量时,如 mutate(.data[[x_value]] = mpg * 10) %>% 中所示:
Error: unexpected '=' in:
"data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(.data[[x_value]] ="
显而易见的问题:为什么这不起作用? 以及明显的后续:如何使用变量来指定要变异的列?
作为参考,工作示例:
#// 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`")
#// add variable into mutate assigment
data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
mutate(mpg = .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`")
由reprex package (v0.3.0) 于 2021-01-13 创建
【问题讨论】: