简体   繁体   中英

using variable with .data[[]] in mutate in dplyr

I thought with my previous questions I had sorted out all issues in using variables in the tidyverse. But I just ran into a problem using the mutate function I do not understand. Below is a toy-example of piping a dplyr statement into ggplot.

I added an explicit mutate step mutate(mpg = mpg * 10) %>% which works just fine.

Also adding in the column by name with .data[[]] on the RHS of the statement works fine using mutate(mpg =.data[[x_value]] * 10) %>% .

However, when I use a variable on the LHS of the equation with .data[[]] or !!sym() as in mutate(.data[[x_value]] = mpg * 10) %>% I get:

Error: unexpected '=' in:
"data %>% filter( .data[[remove_col]] != {{ remove_val }} ) %>%
        mutate(.data[[x_value]] ="

The obvious question: Why is this not working? And the obvious follow-up: How can I use a variable to designate a column to mutate?


For reference, the working examples:

#// 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`")

Created on 2021-01-13 by the reprex package (v0.3.0)

Things are handled differently depending on whether you have a variable on LHS or RHS. If you have a variable on LHS use :.variable_name.=.... where variable_name should be a string value.

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`")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM