如何使用dplyr使用非标准评估来评估构造的字符串? [英] How to evaluate a constructed string with non-standard evaluation using dplyr?

查看:68
本文介绍了如何使用dplyr使用非标准评估来评估构造的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经阅读了有关使用 dplyr 进行编程的几本指南,但对于如何解决使用非标准评估(NSE)评估构造/串联字符串的问题,我仍然感到困惑.我意识到有比使用NSE更好的方法来解决此示例,但想学习如何使用.

I have read several guides on programming with dplyr now and I am still confused about how to solve the problem of evaluating constructed/concatenated strings with non-standard evaluation (NSE). I realize that there are better ways to solve this example than using NSE, but want to learn how to.

t <- tibble( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
i <- 1

这是我想要的结果,但是希望构造mutate()中的变量:

This is my desired outcome but want the variables in mutate() to be constructed:

t %>% mutate(d_01 = x_01 * 2)
#>   A tibble: 3 x 3
#>   x_01  x_02  d_01
#>   <dbl> <dbl> <dbl>
#> 1  1.00  4.00  2.00
#> 2  2.00  5.00  4.00
#> 3  3.00  6.00  6.00

这是我第一次尝试使用字符串:

This is my first attempt, trying to use strings:

new <- sprintf("d_%02d", i)
var <- sprintf("x_%02d", i)
t %>% mutate(new = var * 2)
#> Error in mutate_impl(.data, dots) : 
#> Evaluation error: non-numeric argument to binary operator.

这是我第二次尝试使用quasures:

This is my second attempt, trying to use quosures:

new <- rlang::quo(sprintf("d_%02d", i))
var <- rlang::quo(sprintf("x_%02d", i))
t %>% mutate(!!new = !!var * 2)
#> Error: unexpected '=' in "t %>% mutate(!!new ="

这是我的第三次尝试,尝试使用quosures和:=运算符:

This is my third attempt, trying to use quosures and the := operator:

new <- rlang::quo(sprintf("d_%02d", i))
var <- rlang::quo(sprintf("x_%02d", i))
t %>% mutate(!!new := !!var * 2)
#> Error in var * 2 : non-numeric argument to binary operator

推荐答案

像这样使用sym:=:

library(dplyr)
library(rlang)

t <- tibble( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
i <- 1

new <- sym(sprintf("d_%02d", i))
var <- sym(sprintf("x_%02d", i))
t %>% mutate(!!new := (!!var) * 2)

给予:

# A tibble: 3 x 3
   x_01  x_02  d_01
  <dbl> <dbl> <dbl>
1     1     4     2
2     2     5     4
3     3     6     6

还要注意,这在基数R中是微不足道的:

Also note that this is trivial in base R:

tdf <- data.frame( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
i <- 1

new <- sprintf("d_%02d", i)
var <- sprintf("x_%02d", i)
tdf[[new]] <- 2 * tdf[[var]]

这篇关于如何使用dplyr使用非标准评估来评估构造的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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