RStudio 和 R 中波浪号扩展的区别

Difference between tilde expansion in RStudio and R

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

让 RStudio 和 R 就如何扩展波浪号达成一致的最佳方法是什么?

正如@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)
}

将其扩展到跨平台工作应该很简单。