【问题标题】:R commandline arguments and makefileR 命令行参数和生成文件
【发布时间】:2012-02-12 08:29:14
【问题描述】:

我在组合 makefile 和接受命令行参数的 R 程序时遇到问题。

一个例子: 我编写了一个 R 文件,它接受命令行参数并生成一个绘图。

代码

    args <- commandArgs(trailingOnly=TRUE)
    if (length(args) != 1) {
    cat("You must supply only one number\n")
    quit()
    }
    inputnumber <- args[1]
    pdf("Rplot.pdf")
    plot(1:inputnumber,type="l")
    dev.off()

生成文件

all : make Rplot.pdf
Rplot.pdf : test.R
        cat test.R | R --slave --args 10

现在的问题是如何提供 --args(在这种情况下为 10),这样我就可以这样说: make Rplot.pdf -10

我理解它更多的是Makefile 问题而不是R 问题。

【问题讨论】:

    标签: r makefile


    【解决方案1】:

    您有两个问题。

    第一个问题是关于命令行参数解析的,我们已经在网站上提出了几个问题。请搜索“[r] optparse getopt”以查找例如

    还有更多。

    第二个问题涉及基本的 Makefile 语法和用法,是的,网上也有很多教程。你基本上提供它们类似于 shell 参数。这是例如我的 Makefile 的一部分(来自RInside 的示例),我们在其中查询 R 到命令行标志等:

    ## comment this out if you need a different version of R, 
    ## and set set R_HOME accordingly as an environment variable
    R_HOME :=       $(shell R RHOME)
    
    sources :=      $(wildcard *.cpp)
    programs :=     $(sources:.cpp=)
    
    
    ## include headers and libraries for R 
    RCPPFLAGS :=    $(shell $(R_HOME)/bin/R CMD config --cppflags)
    RLDFLAGS :=     $(shell $(R_HOME)/bin/R CMD config --ldflags)
    RBLAS :=        $(shell $(R_HOME)/bin/R CMD config BLAS_LIBS)
    RLAPACK :=      $(shell $(R_HOME)/bin/R CMD config LAPACK_LIBS)
    
    ## include headers and libraries for Rcpp interface classes
    RCPPINCL :=     $(shell echo 'Rcpp:::CxxFlags()' | \
                               $(R_HOME)/bin/R --vanilla --slave)
    RCPPLIBS :=     $(shell echo 'Rcpp:::LdFlags()'  | \
                               $(R_HOME)/bin/R --vanilla --slave)
    
    
    ## include headers and libraries for RInside embedding classes
    RINSIDEINCL :=  $(shell echo 'RInside:::CxxFlags()' | \
                                $(R_HOME)/bin/R --vanilla --slave)
    RINSIDELIBS :=  $(shell echo 'RInside:::LdFlags()'  | \
                                $(R_HOME)/bin/R --vanilla --slave)
    
    [...]
    

    【讨论】:

      【解决方案2】:

      您可以如下定义命名参数:

      $ cat Makefile 
      all:
          echo $(ARG)
      
      $ make ARG=1 all
      echo 1
      1
      

      您也可以使用Rscript test.R 10 代替cat test.R | R --slave --args 10

      【讨论】:

      • 您好,谢谢您的回答。但问题是如何通过 Makefile 提供参数?我在我的 test.R 文件中使用 commandArgs()
      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2012-10-22
      • 2016-03-25
      相关资源
      最近更新 更多