Reputation: 89057
In R, I can set environment variables "manually", for example:
Sys.setenv(TODAY = "Friday")
But what if the environment variable name and value are stored in R objects?
var.name <- "TODAY"
var.value <- "Friday"
I wrote this:
expr <- paste("Sys.setenv(", var.name, " = '", var.value, "')", sep = "")
expr
# [1] "Sys.setenv(TODAY = 'Friday')"
eval(parse(text = expr))
which does work:
Sys.getenv("TODAY")
# 1] "Friday"
but I find it quite ugly. Is there a better way? Thank you.
Upvotes: 22
Views: 12485
Reputation: 9582
This is a variant of the accepted answer, but if you want to pack this into a single line, and/or avoid generating the intermediate args
object, you can use setNames
to get a named character vector, then coerce to list with as.list
:
do.call(Sys.setenv, as.list(setNames(var.value, var.name)))
Upvotes: 2
Reputation: 78600
You can use do.call
to call the function with that named argument:
args = list(var.value)
names(args) = var.name
do.call(Sys.setenv, args)
Upvotes: 23