20

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.

flodel
  • 87,577
  • 21
  • 185
  • 223

3 Answers3

22

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)
David Robinson
  • 77,383
  • 16
  • 167
  • 187
6

Try this:

.Internal(Sys.setenv(var.name, var.value))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • 2
    +1 but don't do this in a package, as it's against CRAN policies. – Joshua Ulrich Sep 21 '12 at 17:52
  • @JoshuaUlrich, can you please elaborate on your comment? Is it because `.Internal` functions are not subject to the same (strict) backward compatibility requirements? – flodel Sep 21 '12 at 17:55
  • 3
    @flodel: see the [CRAN Repository Policy](http://cran.r-project.org/web/packages/policies.html): "CRAN packages should use only the public API..." – Joshua Ulrich Sep 21 '12 at 17:57
1

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)))
arvi1000
  • 9,393
  • 2
  • 42
  • 52