4

On (my install of) RStudio on Windows path.expand("~") returns "C:/Users/myusername/Documents". However RScript -e path.expand('~') from the command line returns "C:\Users\myusername" (the same from the R REPL). This makes scripts that use a tilde and work in one environment fail in the other. A possible fix is to execute set R_USER=C:\Users\myusername\Documents before running the script from the command line, but this seems like a kludge; it also might trip up other users of my script unless I warn them to set R_USER. I also tried adding an entry to ~/.Renviron but that seemed to cause the 'Source' button in RStudio to fail.

What is the best way to make RStudio and R agree on how to expand tilde?

banbh
  • 1,331
  • 1
  • 13
  • 31
  • Could it be that RStudio uses a different version of R? – krlmlr Aug 31 '15 at 14:04
  • @krlmlr Good point. However it looks like both use the same version of R. `sessionInfo()` in both cases produces `R version 3.2.1 (2015-06-18) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1`. – banbh Aug 31 '15 at 14:19
  • 1
    Look at `Sys.getenv("R_USER")` in both `Rscript` and RStudio. Set it explicitly in `.Renviron` – hrbrmstr Aug 31 '15 at 14:21
  • 1
    I would say, don't rely on expansion, never. Use a fixed path (maybe asking the user) or an environment variable (but again this may change depending on how the program is called) – Tensibai Aug 31 '15 at 14:25
  • @Tensibai I think not relying on tilde expansion makes sense. I'll answer my question with a fleshed-out version of this. – banbh Aug 31 '15 at 15:32

1 Answers1

1

As suggested by @Tensibai, not relying on tilde-expansion might be the best solution. Instead I'm using the following function:

Home <- function() {
  # Returns a string with the user's home directory
  #
  # Serves as a replacement for "~", and works both in RStudio and RScript.
  #
  # Returns:
  #   On Windows returns C:/Users/<username>, where <username> is the current user's username.

  normalizePath(file.path(Sys.getenv("HOMEDRIVE"), Sys.getenv("HOMEPATH")), winslash = .Platform$file.sep)
}

It should be straightforward to extend this to work cross-platform.

banbh
  • 1,331
  • 1
  • 13
  • 31