sayan dasgupta
sayan dasgupta

Reputation: 1082

R commandline arguments and makefile

I am having a problem combining makefile and R program which accepts command line arguments.

An example: I have written an R file that accepts a command line argument and generates a plot.

Code

    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()

Makefile

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

Now the question is how to supply --args (10 in this case), so that I can say something like this: make Rplot.pdf -10

I understand its more a Makefile question rather an R question.

Upvotes: 1

Views: 1685

Answers (2)

Dirk is no longer here
Dirk is no longer here

Reputation: 368579

You have two questions here.

The first question is about command-line argument parsing, and we already had several questions on that on the site. Please do a search for "[r] optparse getopt" to find e.g.

and more.

The second question concerns basic Makefile syntax and usage, and yes, there are also plenty of tutorials around the net. And you basically supply them similar to shell arguments. Here is e.g. a part of Makefile of mine (from the examples of RInside) where we query R to command-line flags etc:

## 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)

[...]

Upvotes: 5

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32401

You can define named arguments as follows:

$ cat Makefile 
all:
    echo $(ARG)

$ make ARG=1 all
echo 1
1

You can also use Rscript test.R 10 instead of cat test.R | R --slave --args 10 .

Upvotes: 2

Related Questions