Aye*_*aid 4 command-line arguments r window rscript
我的桌面上有一个 rscript (file.r),其中包含一个函数。我需要从 Windows 命令提示符调用这个函数并将参数传递给它,我找到了这种方式,但我不明白它是如何使用的,比如它是什么意思?
我已经有了 R 的外壳,但我需要从 Windows 命令提示符执行它,而不是 R 本身
args <- commandArgs(trailingOnly = TRUE)
Run Code Online (Sandbox Code Playgroud)
你有你的 R 脚本(test.R),例如:
#commandArgs picks up the variables you pass from the command line
args <- commandArgs(trailingOnly = TRUE)
print(args)
Run Code Online (Sandbox Code Playgroud)
然后使用以下命令从命令行运行脚本:
#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"
Run Code Online (Sandbox Code Playgroud)
然后你得到的是一个包含 2 个元素的向量,即 5 和 6。trailingOnly = TRUE确保你只得到 5 和 6 作为参数。如果省略它,则变量 args 还将包含有关调用的一些详细信息:
例如检查这个。我的 R 脚本是:
args <- commandArgs()
print(args)
Run Code Online (Sandbox Code Playgroud)
调用返回:
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"
Run Code Online (Sandbox Code Playgroud)
我没有包括trailingOnly = TRUE这里,我也收到了一些电话详情。