如何让 `str_glue()` 区分参数及其值?

How to get `str_glue()` to discriminate between an argument and its value?

背景:sfun是一个变异mtcars的函数。 sfun 有一个 cyl 参数,它与 mtcars 中的 cyl 向量同名。

问题:当 sfun(cyl = "hp") 时,如何启用 str_glue() 来区分参数 (cyl) 和它的值 (hp)?

sfun <- function(mydf, cyl){
  myoutput <- 
    mydf %>% 
    mutate(attempt1 = sprintf("%s shows hp values", !!sym(cyl)))  %>%  ## this works
    mutate(attempt2 = str_glue("{cyl} does not show hp values "))
  return(myoutput)
}
mtcars %>% dplyr::select(cyl, hp) %>% head(5) %>% sfun(cyl="hp")

> mtcars %>% dplyr::select(cyl, hp) %>% head(5) %>% sfun(cyl="hp")
                  cyl  hp            attempt1                   attempt2
Mazda RX4           6 110 110 shows hp values 6 does not show hp values 
Mazda RX4 Wag       6 110 110 shows hp values 6 does not show hp values 
Datsun 710          4  93  93 shows hp values 4 does not show hp values 
Hornet 4 Drive      6 110 110 shows hp values 6 does not show hp values 
Hornet Sportabout   8 175 175 shows hp values 8 does not show hp values 
> 
 

实现您想要的结果的一个选择是使用来自 rlang:

.data.env 代词
  • .data 将从数据中选取列
  • .env 将从环境中选取变量

参见例如这个blog post

library(stringr)
library(dplyr)

sfun <- function(mydf, cyl){
  mydf %>% 
    #mutate(attempt1 = sprintf("%s shows hp values", !!sym(cyl)))  %>%  ## this works
    mutate(attempt2 = str_glue("{.data[[.env$cyl]]} does not show hp values "))
}
mtcars %>% dplyr::select(cyl, hp) %>% 
  head(5) %>% 
  sfun(cyl = "hp")
#>                   cyl  hp                     attempt2
#> Mazda RX4           6 110 110 does not show hp values 
#> Mazda RX4 Wag       6 110 110 does not show hp values 
#> Datsun 710          4  93  93 does not show hp values 
#> Hornet 4 Drive      6 110 110 does not show hp values 
#> Hornet Sportabout   8 175 175 does not show hp values