我如何向桌面上的R脚本传递参数?

9

我有一个文件.r的R脚本保存在我的桌面上,其中包含一个函数。我需要从Windows命令提示符中调用这个函数并传递参数给它,我已经找到了一种方法,但我不明白它是如何使用的,比如它是什么意思?
我已经安装了R的Shell,但我需要从Windows命令提示符中执行它,而不是在R中执行。

args <- commandArgs(trailingOnly = TRUE)
1个回答

19

您有一个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,结果返回了一些通话细节。


1
你好,非常棒的答案,非常感谢,它已经帮助了我。您能否展示如何将它们作为命名参数传递?--first 5 --second 6 预先致谢! - Sos

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