【问题标题】:R shell.exec requires full file pathR shell.exec 需要完整的文件路径
【发布时间】:2019-11-21 08:30:26
【问题描述】:

本周我在一台新的 Windows 10 机器上安装了 R 和 RStudio。我想使用这个 R 代码来启动 Excel 并打开一个位于当前工作目录子目录中的 CSV 文件:

file <- "example.csv"
sub_dir <- "subdirectory"
shell.exec(file.path(sub_dir, file))

但我收到此错误:

Error in shell.exec(file.path(sub_dir, file)) : 
  'subdirectory/example.csv' not found

但是,如果我向shell.exec 提供完整的文件路径,则此代码将按预期工作:

shell.exec(file.path(getwd(), sub_dir, file))

shell.exec 的文档指出:

文件中的路径是相对于当前工作的 目录。

相对于 R 主页的 R 版本 2.13.0 和更早版本的解释文件 目录,因此通常需要完整的路径。

为什么我的原始代码(没有getwd)不起作用?谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    它看起来以某种古怪的方式与路径分隔符相关。下面,我将文件路径分隔符指定为\,命令按预期执行。您可以继续拨打file.path() 并简单地将normalizePath() 作为另一种选择。

    file <- "example.csv"
    sub_dir <- "subdirectory"
    dir.create(sub_dir)
    writeLines("myfile",file.path(sub_dir, file))
    # Works
    shell.exec(file.path(sub_dir, file, fsep = "\\"))
    shell.exec(file.path(sub_dir, file))
    #> Error in shell.exec(file.path(sub_dir, file)): 'subdirectory/example.csv' not found
    
    

    【讨论】:

    • normalizePath 替换正斜杠并完成完整路径。我会坚持使用getwd 并提交错误/文档错误报告。
    • 它可能会完成路径,但如果您在 Windows 上,则不应使用正斜杠。其中,AFAICT,是 shell.exec 工作的唯一系统。另外,我的其他建议没有完成完整路径。
    • 明确地说,我同意你的观点,shell.exec 不像记录的那样工作。
    • 我之前的评论并不清楚。我应该说 normalizePath 用反斜杠替换正斜杠; normalizePath(file.path(sub_dir, file)) 生成“C:\\path_to_current_working_directory\\subdirectry\\example.csv”
    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多