如何将参数传递给桌面上的 Rscript?

How can I pass arguments to an Rscript i have in my desktop?

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

args <- commandArgs(trailingOnly = TRUE)

您有自己的 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)

然后调用 returns:

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,但我也收到了一些通话详细信息。