How to use dplyr programming syntax to create and evaluate variable names

安稳与你 提交于 2019-12-01 17:27:53

问题


I would like to dynamically input a variable name using dplyr programming syntax, however, as many have described this can be quite confusing.

I've played around with various combinations of quo/enquo !! etc. to no avail. Here is the simplest form of my code

library(tidyverse)

df <- tibble(
  color1 = c("blue", "blue", "blue", "blue", "blue"),
  color2 = c("black", "black", "black", "black", "black"),
  value = 1:5
)

num <- 2

df %>%
  mutate(color3 = !!(paste0("color", num)))


#> # A tibble: 5 x 4
#>   color1 color2 value color3
#>   <chr>  <chr>  <int> <chr> 
#> 1 blue   black      1 color2
#> 2 blue   black      2 color2
#> 3 blue   black      3 color2
#> 4 blue   black      4 color2
#> 5 blue   black      5 color2

Created on 2018-12-19 by the reprex package (v0.2.1)

Instead I would like to evaluate the quoted input.

#> # A tibble: 5 x 4
#>   color1 color2 value color3
#>   <chr>  <chr>  <int> <chr> 
#> 1 blue   black      1 black 
#> 2 blue   black      2 black 
#> 3 blue   black      3 black 
#> 4 blue   black      4 black 
#> 5 blue   black      5 black

回答1:


We can use sym from rlang to convert the string to symbol and then evaluate (!!)

library(dplyr)
df %>%
   mutate(color3 = !!(rlang::sym(paste0("color", num))))
# A tibble: 5 x 4
#  color1 color2 value color3
#  <chr>  <chr>  <int> <chr> 
#1 blue   black      1 black 
#2 blue   black      2 black 
#3 blue   black      3 black 
#4 blue   black      4 black 
#5 blue   black      5 black 


来源:https://stackoverflow.com/questions/53859015/how-to-use-dplyr-programming-syntax-to-create-and-evaluate-variable-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!