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

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

如何使RStudio和R达成一致以扩展波浪号(tilde)的最佳方法是什么?


RStudio使用的R版本可能不同吗? - krlmlr
@krlmlr 说得好。但是看起来两者都使用相同版本的R。在这两种情况下,sessionInfo()都会生成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
1
Rscript和RStudio中查看Sys.getenv("R_USER")。在.Renviron文件中明确设置它。 - hrbrmstr
1
我会说,永远不要依赖于扩展。使用固定路径(也许询问用户)或环境变量(但这可能会根据程序的调用方式而改变)。 - Tensibai
@Tensibai 我认为不依赖波浪号扩展是有道理的。我会用更详细的版本回答我的问题。 - banbh
1个回答

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

这应该很简单,可以扩展到跨平台工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接