Search code examples
rnamespacesr-environmentr-glue

Better way to deal with namespace when using glue::glue


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?


Solution

  • 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