How to force ev <- Sys.getenv() to evaluate at run time?

Its hard to do a reprex for this, so I'll do my best to explain.

I have a mixture of scripts and functions in a utils.R file as part of a package. All its content is intended to be for internal use and not exported. One line is causing me headaches.

# magic vars ====
#' @noRd
#' @importFrom magrittr %>%
#' @importFrom stringr str_to_lower
t1.label. <- Sys.getenv("T1_LABEL") %>% str_to_lower()

It seems the assignment is evaluated at build time. I've tried force()

t1.label. <- force(Sys.getenv("T1_LABEL")) %>% str_to_lower()

but this doesn't make any difference. How can I get the assignment to be made against the env. variables on the machine (usually a Docker container) that the package is deployed to?

One trick that might help (assuming that I am answering to the right question) is to create an environment variable with new.env() and update values inside that environment using .onLoad() or .onAttach() Ref: http://r-pkgs.had.co.nz/r.html

1 Like

If you want to delay the evaluation till run time, make it a function. Then it can't run till run-time.

t1.label <- function() Sys.getenv("T1_LABEL") %>% str_to_lower()

and then you'll just have to get it's current value with t1.label(). (because the environment variable can change, you'll get whatever the current value is at the time you call the function).

Or if you want to run this code when a package loads, you can also set up an .onLoad function for your package. Some thing like

.onLoad <- function(libname, pkgname){
  t1.label. <<- Sys.getenv("T1_LABEL") %>% str_to_lower()
}

see: https://stackoverflow.com/questions/20223601/r-how-to-run-some-code-on-load-of-package

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.