0

I want to create a function that itself uses the awesome glue::glue function.

However, I came to find myself dealing with some namespace issue when I want to glue a variable that exists in both function and global environments:

x=1

my_glue <- function(x, ...) {
    glue::glue(x, ...)
}
my_glue("foobar x={x}") #not the expected output
# foobar x=foobar x={x}

I'd rather keep the variable named x for package consistency.

I ended up doing something like this, which works pretty well so far but only postpone the problem (a lot, but still):

my_glue2 <- function(x, ...) {
    x___=x; rm(x)
    glue::glue(x___, ...)
}
my_glue2("foobar x={x}") #problem is gone!
# foobar x=1
my_glue2("foobar x={x___}") #very unlikely but still...
# foobar x=foobar x={x___}

Is there a better/cleaner way to do this?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92

1 Answers1

2

Since the value x = 1 is nowhere passed to the function, in the current scenario a way to do this would be to evaluate the string in the global environment itself where the value of x is present before passing it to the function.

my_glue(glue::glue("foobar x={x}"))
#foobar x=1

my_glue(glue::glue("foobar x={x}"), " More text")
#foobar x=1 More text

Another option (and I think this is the answer that you are looking for) is to get the value of x from the parent environment. glue has .envir parameter, where the environment to evaluate the expression can be defined.

my_glue <- function(x, ...) {
   glue::glue(x, ...,.envir = parent.frame())
}
my_glue("foobar x={x}")
#foobar x=1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I think you would want to use `.envir = parent.frame()` instead of hardcoding the `.GlobalEnv` – Tyler Smith Mar 08 '20 at 11:30
  • @TylerSmith yes, a better option. Updated the answer. – Ronak Shah Mar 08 '20 at 12:19
  • Awesome, thanks. Indeed, the first option is not what I'm looking for and makes the whole function quite useless. I'm quite surprised though, isn't `.envir = parent.frame()` the default in `glue`? – Dan Chaltiel Mar 08 '20 at 18:28
  • Yeah, I thought the same initially hence I hard-coded `.GlobalEnv`. Turns out it isn't how it works. Strange. – Ronak Shah Mar 08 '20 at 22:43