如何将使用enquo()创建的动态变量名称传递给dplyr的mutate进行评估? [英] How do I pass a dynamic variable name created using enquo() to dplyr's mutate for evaluation?

查看:57
本文介绍了如何将使用enquo()创建的动态变量名称传递给dplyr的mutate进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个工作流,其中包含相同的管道步骤,包括重命名,选择方式,然后使用我在管道之前提供的名称进行全部变异.

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.

我已经成功地使用 enquo() !! (bang bang)重命名为所需的字符串,然后再次选择它,但是当我到达mutate时步骤,它要么重复文本字符串作为列值,要么不求值.

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

我可以使用 quo_name():=

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

我可以使用 !!

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

但是我不能然后在mutate中调用该列并使用值

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

推荐答案

"new_var"对象是字符串上的 quosure .提取字符串,将其转换为符号,然后进行评估

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


此外,如果我们以 quosure 中的 new_var 取消引用开头,则OP的代码有效


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

这篇关于如何将使用enquo()创建的动态变量名称传递给dplyr的mutate进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆