R脚本使用commandArgs()获取命令行参数异常问题咨询
Hey there! I totally get why this is confusing—let's break down what's happening and fix it quickly.
The Root Cause
When you use commandArgs() without any extra arguments, it returns every single parameter passed to the R interpreter when you run your script. That includes:
- Default flags Rscript adds automatically (like
--slave,--no-restore) - The path to your script (
--file=./wtf.r) - Then your custom arguments (
arg1,arg2,arg3)
Your current code is grabbing the 2nd, 3rd, and 4th elements of this full list, which just happen to be those system flags instead of your inputs.
The Fix: Use trailingOnly = TRUE
R's commandArgs() has a handy parameter called trailingOnly—set it to TRUE, and it will only return the arguments that come after your script name. No more guessing which index to pick!
Here's your modified script:
#!/usr/bin/Rscript args = commandArgs(trailingOnly = TRUE) asdf = list() asdf$arg1 = args[1] # Now the first element is your first custom arg asdf$arg2 = args[2] asdf$arg3 = args[3] print(asdf)
Test It Out
Run your script again with:
my@comp:~/wtfdir$ ./wtf.r arg1 arg2 arg3
You'll get the output you expect:
$arg1 [1] "arg1" $arg2 [1] "arg2" $arg3 [1] "arg3"
Bonus Tip
If you ever want to see the full list of arguments R is receiving (including system flags), just run print(commandArgs()) in your script. And for more details, you can always check R's built-in help with ?commandArgs directly in the R console.
内容的提问来源于stack exchange,提问作者user4385532

