简体   繁体   中英

Assign new variable created with mutate_ to a name that will be passed as a string in dplyr

I want to use strings with dplyr expressions and in particular I want to pass expressions as strings to mutate to create new variables and assign names to these variables that will be passed also as strings.

My code at this point is the following:

library(dplyr)
library(tidyverse)

data(mtcars)

mutate_expr = "gear * carb"

mtcars %>% mutate_(mutate_expr)

The new variable is named here 'gear*carb'. How I could give it the name 'gear_carb' passing the name to the dplyr expression as a string?

You now do this with tidyeval :

library(dplyr)

mutate_expr <- quo(gear * carb)

mtcars %>% mutate(new_col = !!mutate_expr) %>% head()
#>     mpg cyl  disp  hp drat    wt  qsec vs am gear carb new_col
#> 1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      16
#> 2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4      16
#> 3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1       4
#> 4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1       3
#> 5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2       6
#> 6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1       3

If you must store the expression as a string, you can use sym instead of quo (really rlang::parse_expr in this context), but storing code as a character string is a bad idea.

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