Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make R script takes input from pipe and user given parameter

I have the following R script (myscript.r)

#!/usr/bin/env Rscript
dat <- read.table(file('stdin'), sep=" ",header=FALSE)
# do something with dat
# later with user given "param_1" 

With that script we can run it the following way;

$ cat data_no_*.txt | ./myscript.r

What I want to do is to make the script takes additional parameter from user:

$ cat data_no_*.txt | ./myscript.r param_1

What should I do to modify the myscript.r to accommodate that?

like image 683
neversaint Avatar asked Dec 11 '25 10:12

neversaint


2 Answers

For very basic usage, have a look at ?commandArgs.

For more complex usage, two popular packages for command-line arguments and options parsing are getopt and optparse. I use them all the time, they get the job done. I also see argparse, argparser, and GetoptLong but have never used them before. One I missed: Dirk recommended that you look at docopt which does seem very nice and easy to use.

Finally, since you seem to be passing arguments via pipes you might find this OpenRead() function useful for generalizing your code and allowing your arguments to be pipes or files.


I wanted to test docopt so putting it all together, your script could look like this:

#!/usr/bin/env Rscript

## Command-line parsing ##

'usage: my_prog.R [-v -m <msg>] <param> <file_arg> 

options:
 -v        verbose
 -m <msg>  Message' -> doc

library(docopt)
opts <- docopt(doc)

if (opts$v) print(str(opts)) 
if (!is.null(opts$message)) cat("MESSAGE: ", opts$m)

## File Read ##

OpenRead <- function(arg) {
   if (arg %in% c("-", "/dev/stdin")) {
      file("stdin", open = "r")
   } else if (grepl("^/dev/fd/", arg)) {
      fifo(arg, open = "r")
   } else {
      file(arg, open = "r")
   }
}

dat.con <- OpenRead(opts$file_arg)
dat <- read.table(dat.con, sep = " ", header = FALSE)

# do something with dat and opts$param

And you can test running:

echo "1 2 3" | ./test.R -v -m HI param_1 -

or

./test.R -v -m HI param_1 some_file.txt
like image 71
flodel Avatar answered Dec 12 '25 23:12

flodel


We built littler to support just that via its r executable.

Have a look at its examples, it may fit your bill.

like image 42
Dirk Eddelbuettel Avatar answered Dec 13 '25 01:12

Dirk Eddelbuettel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!