RStudio中的波浪扩展与R的区别

时间:2015-08-31 13:52:07

标签: r windows rstudio

On(我的安装)Windows上的RStudio path.expand("~")返回“C:/ Users / myusername / Documents”。但是,命令行中的RScript -e path.expand('~')返回“C:\ Users \ myusername”(与R REPL相同)。这使得使用代字号并在一个环境中工作的脚本在另一个环境中失败。一个可能的解决方法是在从命令行运行脚本之前执行set R_USER=C:\Users\myusername\Documents,但这看起来像一个kludge;它也可能会绊倒我脚本的其他用户,除非我警告他们设置R_USER。我也尝试在~/.Renviron添加一个条目,但这似乎导致RStudio中的“Source”按钮失败。

让RStudio与R达成如何扩展波形符的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

正如@Tensibai所建议的那样,不依赖波浪扩展可能是最好的解决方案。相反,我使用以下功能:

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)
}

将其扩展到跨平台工作应该是直截了当的。