【问题标题】:using variable with .data[[]] in mutate in dplyr在 dplyr 的 mutate 中使用带有 .data[[]] 的变量
【发布时间】: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 创建

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    根据您在 LHS 或 RHS 上是否有变量,处理方式会有所不同。如果您在 LHS 上有一个变量,请使用 !!variable_name := .... 其中variable_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`")
    

    【讨论】:

    • 啊!!我记得以前见过这种语法,但并没有真正得到。我想这只是要记住的另一件事。而且我猜在我过去使用 .data[[x]] 的 tidy-select 函数中,它总是在条件语句中,而不是在为变量赋值。
    猜你喜欢
    • 2018-05-06
    • 2019-01-21
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多