How do I pass a dynamic variable name created using enquo() to dplyr's mutate for evaluation?

人走茶凉 提交于 2021-02-05 07:26:05

问题


I'm creating a workflow that contains the same piping steps of renaming, selecting by, then mutating all using a name I provide prior to the pipe.

I have had success using enquo() and !!(bang bang) to rename to my desired string and then select it again, but when I reach the mutate step it either repeats the text string as the column values or will not evaluate.

I've recreated the code below:

#Testing rename, select, and mutate use cases for enquo()

#Load packages
library(dplyr)
library(rlang)
library(magrittr)

#Create name I want to pass
new_var <- quo("new_name")

#Create Test Data
t1 <- tibble(Year = c(2000:2004),
             old_name = c(NA, 1, 1, 1, NA))

I can rename the column with quo_name() and :=

t1 %>% 
  rename( !! quo_name(new_var) := old_name)

I can select on it using !!

t1 %>% 
  rename( !! quo_name(new_var) := old_name) %>% 
  select(Year, !!new_var)

But I can't then call that column in mutate and use the values

t1 %>% 
  rename( !! quo_name(new_var) := old_name) %>% 
  select(Year, !!new_var) %>% 
  mutate(test_var = (!! new_var))

回答1:


The 'new_var' object is a quosure on a string. Extract the string, convert it to symbol and then do the evaluation

t1 %>% 
   rename( !! quo_name(new_var) := old_name) %>% 
   select(Year, !!new_var) %>% 
   mutate(testvar = !! rlang::sym(rlang::quo_name(new_var)))
# A tibble: 5 x 3
#   Year new_name testvar
#  <int>    <dbl>   <dbl>
#1  2000       NA      NA
#2  2001        1       1
#3  2002        1       1
#4  2003        1       1
#5  2004       NA      NA

Also, if we start with unquoted the new_var in quosure, then the OP's code works

new_var = quo(new_name)
t1 %>% 
     rename(!! new_var := old_name) %>% 
     select(Year, !!new_var) %>% 
     mutate(testvar = !! new_var)
# A tibble: 5 x 3
#   Year new_name testvar
#  <int>    <dbl>   <dbl>
#1  2000       NA      NA
#2  2001        1       1
#3  2002        1       1
#4  2003        1       1
#5  2004       NA      NA



回答2:


Try replacing the first line with:

new_var <- sym("new_name")

In this case your existing code should run, but you could also simplify it, e.g.:

t1 %>% 
  rename( !! new_var := old_name) %>% 
  select(Year, !! new_var) %>% 
  mutate(test_var = (!! new_var))


来源:https://stackoverflow.com/questions/54575680/how-do-i-pass-a-dynamic-variable-name-created-using-enquo-to-dplyrs-mutate-fo

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