Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Passing parameters to R script

by j1n3l0 (Friar)
on Oct 15, 2007 at 15:41 UTC ( #644967=perlquestion: print w/replies, xml ) Need Help??
j1n3l0 has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

Forgive me in advance here but I need a little help in R. Does anybody know how to pass parameters to an R script and use them within the script? If I were to do this in Perl it would go like so:

#!/usr/bin/perl -w use strict; use Data::Dumper; my $x = shift; # ... then i can play with $x here my @xvalues = (1 .. $x); my @yvalues = map { $_ ** 2 } @xvalues; print Dumper \@xvalues, \@yvalues; exit (0);

So how can I do this in R? The documentation says to use args <- commandArgs(TRUE) but does not really say more than that. What I've got so far is something like this:

#args <- commandArgs(TRUE) # This works okay but I would like to replace 10 as a parameter though x <- c(1:10) y <- c(x^2) png(filename="plot.png", bg="transparent") plot(x, y)

Any help is much appreciated =)

Smoothie, smoothie, hundre prosent naturlig!

Replies are listed 'Best First'.
Re: Passing parameters to R script
by erix (Vicar) on Oct 15, 2007 at 19:06 UTC

    # test.R:

    cat("-- reading arguments\n", sep = ""); cmd_args = commandArgs(); for (arg in cmd_args) cat(" ", arg, "\n", sep="");

    # command line:

    R --slave --no-save --no-restore --no-environ --silent --args arg1=abc + < test.R

    # output from R:

    -- reading arguments /home/aardvark/lib/R/bin/exec/R --slave --no-save --no-restore --no-environ --silent --args arg1=abc
      Thank you very much! This is precisely what I was looking for =)

      Now I need to tweak it a bit for my needs. Thank you soooooooooo much!

      Smoothie, smoothie, hundre prosent naturlig!
        very late answer, maybe the library is newer than your question, but what about optparse or getopt?
        install.packages('optparse') ?optparse
        I tried to get it working (I come from Python and I'm used to the syntax) but in the end I settled for the easier (and working) 'getopt' solution:
        install.packages('getopt') . . . if(require("getopt", quietly=TRUE)) { opt <- getopt(matrix(c('path', 'p', 1, "character"), ncol=4, byrow=TRUE)) if(!is.null(opt$path)) path <- opt$path }
Re: Passing parameters to R script
by perlfan (Curate) on Oct 15, 2007 at 16:49 UTC
Re: Passing parameters to R script
by toolic (Bishop) on Oct 15, 2007 at 16:55 UTC
    Since I have no experience with R, I can not answer your question directly.

    However, have you considered using Perl to generate your R command input file with whatever parameters you need, then load that new command file into R?

    > cat #!/usr/bin/env perl use warnings; use strict; my $x = shift; my $cmd_file = 'cmd.txt'; open my $OUT_FH, '>', $cmd_file or die "Can not open $cmd_file $!\n"; print $OUT_FH <<"EOF"; x <- c(1:$x) y <- c(x^2) png(filename="plot.png", bg="transparent") plot(x, y) EOF close $OUT_FH or die "Can not close $cmd_file $!\n"; > > ./ 13 > > cat cmd.txt x <- c(1:13) y <- c(x^2) png(filename="plot.png", bg="transparent") plot(x, y) >
      Thank you both

      I have considered doing it this way (writing an R file). I just felt I was not far from the R solution. I know this is not the best place to be asking an R question but I have had useful advice to all my questions in the past I am always compelled to ask here first

      Once again, thank you

      Smoothie, smoothie, hundre prosent naturlig!
Re: Passing parameters to R script
by moklevat (Priest) on Oct 16, 2007 at 17:55 UTC
    Since you appear to be working under Unix, how about:

    ##In a file called test_args.R args <- commandArgs() print (args)

    which you can run from the shell

    cat test_args.R | R --slave --args all your base

    which prints

    [1] "usr/lib64/R/bin/exec/R" "--slave" [3] "--args" "all" [5] "your" "base"
      Thank you all for your input! I did eventually work it out and my solution looks like so:

      # test.R # Parse and use command line arguments # Invoke % R --slave --args 100 < test.R Args <- commandArgs(); # retrieve args x <- c(1:as.real(Args[4])); # get the 4th argument y <- c(x^2); # work out square png(filename="image.png"); # create image file plot(x,y); # plot image
      This creates the image file image.png which contains a plot of an exponential curve =)

      The variable Args contains the following:

      [1] "/usr/lib/R/bin/exec/R" [2] "--slave" [3] "--args" [4] "100"
      We only require the 4th element for our graph. You can add more arguments and just pick them off accordingly =)

      I hope someone else finds this useful.

      Smoothie, smoothie, hundre prosent naturlig!
        Yes, this was very useful and worked right away! Thanks a lot!
        That works fine, but there's a slightly neater way to do it; if you provide a TRUE value to the commandArgs function, it ignores any commandline parameters before (and including) --args.
        So with Args <- commandArgs(TRUE), Args[1] is "100", and is the only element of the vector.

        It's also possible to use a simpler syntax to call the script on the command line, which implicitly assumes that any arguments are given after the script name:
        Rscript test.R 100

        In Rscript/R
        require(plyr) ## get and parse any commandline options/args cmd.args <- commandArgs(trailingOnly=TRUE) ## this assumes trailingOnly in commandArgs() mk.cmd.args.list <- function(args) { if (length(args)>1) { split.list <- strsplit( args[-1], '\\=' ) ## exclude "--args" values <- llply( split.list, '[[', 2 ) names(values) <- laply( split.list, '[[', 1 ) values } else list() ## the possible returns } cmd.args.list <- mk.cmd.args.list(cmd.args)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://644967]
Approved by Old_Gray_Bear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2017-02-25 10:11 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (365 votes). Check out past polls.