狐狸.fox 2010-01-27 23:40 采纳率: 0%
浏览 503
已采纳

如何从 r 脚本中读取命令行参数?

I've got a R script for which I'd like to be able to supply several command-line parameters (rather than hardcode parameter values in the code itself). The script runs on Windows.

I can't find info on how to read parameters supplied on the command-line into my R script. I'd be surprised if it can't be done, so maybe I'm just not using the best keywords in my Google search...

Any pointers or recommendations?

转载于:https://stackoverflow.com/questions/2151212/how-can-i-read-command-line-parameters-from-an-r-script

  • 写回答

10条回答 默认 最新

  • 妄徒之命 2010-01-28 11:47
    关注

    Dirk's answer here is everything you need. Here's a minimal reproducible example.

    I made two files: exmpl.bat and exmpl.R.

    • exmpl.bat:

      set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
      %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
      

      Alternatively, using Rterm.exe:

      set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
      %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
      
    • exmpl.R:

      options(echo=TRUE) # if you want see commands in output file
      args <- commandArgs(trailingOnly = TRUE)
      print(args)
      # trailingOnly=TRUE means that only your arguments are returned, check:
      # print(commandArgs(trailingOnly=FALSE))
      
      start_date <- as.Date(args[1])
      name <- args[2]
      n <- as.integer(args[3])
      rm(args)
      
      # Some computations:
      x <- rnorm(n)
      png(paste(name,".png",sep=""))
      plot(start_date+(1L:n), x)
      dev.off()
      
      summary(x)
      

    Save both files in the same directory and start exmpl.bat. In the result you'll get:

    • example.png with some plot
    • exmpl.batch with all that was done

    You could also add an environment variable %R_Script%:

    "C:\Program Files\R-3.0.2\bin\RScript.exe"
    

    and use it in your batch scripts as %R_Script% <filename.r> <arguments>

    Differences between RScript and Rterm:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 求解答:pytorch跑yolov8神经网络受挫
  • ¥20 Js代码报错问题不知道怎么解决
  • ¥15 gojs 点击按钮node的position位置进行改变,再次点击回到原来的位置
  • ¥15 计算决策面并仿真附上结果
  • ¥20 halcon 图像拼接
  • ¥15 webstorm上开发的vue3+vite5+typeScript打包时报错
  • ¥15 vue使用gojs,需求在link中的虚线上添加方向箭头
  • ¥15 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥100 求ASMedia ASM1184e & ASM1187e 芯片datasheet/规格书