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

前端 未结 1 397
[愿得一人]
[愿得一人] 2021-01-19 02:03

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 wi

相关标签:
1条回答
  • 2021-01-19 02:57

    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 
    
    0 讨论(0)
提交回复
热议问题