You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R脚本使用commandArgs()获取命令行参数异常问题咨询

Why You're Getting System Parameters Instead of Your Custom Args in Rscript

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:14:17