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

Viewed 209

Background: sfun is a function that mutates mtcars. sfun has a cyl arg which shares the same name as the cyl vector in mtcars.

Question: When sfun(cyl = "hp"), how can I enable str_glue() to distinguish the argument (cyl) from its value (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 
> 
 
1 Answers

One option to achieve your desired result would be to make use of the .data and the .env pronouns from rlang:

  • .data will pick columns from the data
  • .env will pick variables from the environment

See e.g. this 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
Related