【问题标题】:How can I pass arguments to an Rscript i have in my desktop?如何将参数传递给桌面上的 Rscript?
【发布时间】:2019-11-06 05:07:05
【问题描述】:

我的桌面上有一个包含函数的 rscript (file.r)。 我需要从 Windows 命令提示符调用这个函数并向它传递参数,我找到了这种方式,但我不明白它是如何使用的,比如它是什么意思?
我已经有了 R 的 shell,但我需要从 Windows 命令提示符下完成,而不是 R 本身

args <- commandArgs(trailingOnly = TRUE)

【问题讨论】:

    标签: r command-line arguments window rscript


    【解决方案1】:

    你有你的 R 脚本 (test.R),例如:

    #commandArgs picks up the variables you pass from the command line
    args <- commandArgs(trailingOnly = TRUE)
    print(args)
    

    然后你从命令行运行你的脚本:

    #here the arguments are 5 and 6 that will be picked from args in the script
    PS C:\Users\TB\Documents> Rscript .\test.R 5 6
    [1] "5"      "6"
    

    那么你得到的是一个包含 2 个元素的向量,即 5 和 6。trailingOnly = TRUE 确保你只得到 5 和 6 作为参数。如果省略它,那么变量 args 还将包含有关调用的一些详细信息:

    例如检查这个。我的 R 脚本是:

    args <- commandArgs()
    print(args)
    

    然后调用返回:

    PS C:\Users\TB\Documents> Rscript .\test.R 5 6
    [1] "C:\\Users\\TB\\scoop\\apps\\anaconda3\\current\\lib\\R\\bin\\x64\\Rterm.exe"
    [2] "--slave"
    [3] "--no-restore"
    [4] "--file=.\\test.R"
    [5] "--args"
    [6] "5"
    [7] "6"
    

    我没有在此处包含trailingOnly = TRUE,并且还返回了一些通话详细信息。

    【讨论】:

    • 嗨,很好的答案,非常感谢,它已经帮助了我。您能否也说明如何将这些作为命名参数传递? --first 5 --second 6提前致谢!
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    相关资源
    最近更新 更多