0% found this document useful (0 votes)
94 views

Passing Arguments To An R Script From Command Lines

Uploaded by

JLAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Passing Arguments To An R Script From Command Lines

Uploaded by

JLAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Passing arguments to an R script from command lines |... https://www.r-bloggers.com/2015/09/passing-argument...

R news and tutorials contribu

HOME ABOUT RSS ADD YOUR BLOG! LEARN R R JOBS CONTACT US

Search R-b
Passing arguments to an R script
from command lines Your e-mail he

Follow
Posted on September 19, 2015 by Nathalie in R bloggers | 0 Comments

[This article was �rst published on tuxette-chix » R, and kindly contributed to R-bloggers]. (You can
report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

 Share  Tweet

This post describes how to pass external arguments to R when calling a Rscript with a
command line. The case study presented here is very simple: a Rscript is called which
Most vie
needs, as an input, a �le name (a text �le containing data which are loaded into R to be
processed) and which can also accept an optional additional argument (an output �le PCA vs Autoe
name: if this argument is not provided, the program supplies one by default). Reduction
How to write
Note: The program just loads a text �le containing data, �lters out non numeric variables 5 Ways to Sub
and writes a text �le with remaining numeric variables only. PowerBI vs. R
Alternatives C
R style 10 Must-Know
relocate()
The most natural way to pass arguments from the command line is to use the function Date Formats
commandArgs . This function scans the arguments which have been supplied when the How to Remo
current R session was invoked. So creating a script named sillyScript.R which starts
with
Sponsors
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)

and running the following command line

1 of 5 12/4/20, 2:21 PM
Passing arguments to an R script from command lines |... https://www.r-bloggers.com/2015/09/passing-argument...

Rscript --vanilla sillyScript.R iris.txt out.txt

will create a string vector args which contains the entries iris.txt and out.txt .
Missing and default arguments can be handled this way:

# test if there is at least one argument: if not, return an error


if (length(args)==0) {
stop("At least one argument must be supplied (input file).n", call.=FALSE)
} else if (length(args)==1) {
# default output file
args[2] = "out.txt"
}

The simple use case described in the introduction thus gives

## program...
df = read.table(args[1], header=TRUE)
num_vars = which(sapply(df, class)=="numeric")
df_out = df[ ,num_vars]
write.table(df_out, file=args[2], row.names=FALSE)

Finally, the command lines

Rscript --vanilla sillyScript.R iris.txt out.txt

or

Rscript --vanilla sillyScript.R iris.txt

will both load the �le iris.txt , �lter out the non numeric variables and write the
resulting data in out.txt . Whereas running

Rscript --vanilla sillyScript.R

Error: At least one argument must be supplied (input file).


Execution halted

python style
One package allows to obtain the same result in a python-like style: the package
optparse. The package can be used to perform a similar task. Basically, the package

2 of 5 12/4/20, 2:21 PM
Passing arguments to an R script from command lines |... https://www.r-bloggers.com/2015/09/passing-argument...

contains the functions

make_option to declare options, their �ags, types, default values and help
messages;
OptionParser to read the arguments passed to the R script and parse_args to
parse them according to what has been declared thanks to make_option .

The functions are used as follows:

#!/usr/bin/env Rscript
Ocean B
library("optparse")

option_list = list( Ocean Ba


make_option(c("-f", "--file"), type="character", default=NULL,
help="dataset file name", metavar="character"),
make_option(c("-o", "--out"), type="character", default="out.txt",
help="output file name [default= %default]", metavar="character"
);

opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);

which produces a list opt that contains all the arguments sorted by order of
appearance in option_list and which can be called by their names as declared in this
object: opt$file and opt$out . Then, managing null arguments is performed as
follows:

if (is.null(opt$file)){
print_help(opt_parser)
stop("At least one argument must be supplied (input file).n", call.=FALSE)
}

in which the function print_help print the help page of the option list as declared in
the object option_list .

The remaining of the function is almost unchanged:

## program...
df = read.table(opt$file, header=TRUE)
num_vars = which(sapply(df, class)=="numeric")
df_out = df[ ,num_vars]
write.table(df_out, file=opt$out, row.names=FALSE)

If the entire script is saved in a �le called yasrs.R ,

3 of 5 12/4/20, 2:21 PM
Passing arguments to an R script from command lines |... https://www.r-bloggers.com/2015/09/passing-argument...

Rscript --vanilla yasrs.R

will give

Usage: testScript.R [options]

Our ads respe


Options: Privacy Policy
-f CHARACTER, --file=CHARACTER
dataset file name
Contact us
-o CHARACTER, --out=CHARACTER R-bloggers, an
output file name [default= out.txt]

-h, --help
Show this help message and exit
Recent P

Tidyverse Tip
Error: At least one argument must be supplied (input file).
BASIC XAI wit
Execution halted
based variabl

and Roger Bivand


with R – retro
Rscript --vanilla yasrs.R --help beakr – A sma
Little useless-
�nder

will print the help Rmd-based R


Python and R
Usage: testScript.R [options] Datatable
2020 Table Co
Options: Gold-Mining W
-f CHARACTER, --file=CHARACTER Małgorzata B
dataset file name
on Sorted L-O
-o CHARACTER, --out=CHARACTER PowerBI vs. R
output file name [default= out.txt]
Alternatives C
-h, --help A Single Param
Show this help message and exit Probability M
Debugging wi
and �nally screencast
DN Unlimited
Rscript --vanilla yasrs.R -f iris.txt
science gathe
Tune and inte
#TidyTuesday
or

Rscript --vanilla yasrs.R -f iris.txt -o out.txt Jobs fo

Junior Data Sc
Senior Quant

4 of 5 12/4/20, 2:21 PM
Passing arguments to an R script from command lines |... https://www.r-bloggers.com/2015/09/passing-argument...

will both create the �le out.txt as described in the introduction of this post. R programme
Data Scientist
My dearest Céline, I hope that this post is explicit enough so that you can make your Agronomy (Re
choice. Now you know that everything can be done with R, even this kind of map. /06/20)
Data Analytics
@ London or
Related

python
(python/

Pandas Group
Docker + Flas
Kernel of erro
How to Scrap
Python
Object Detect
Example of Ce
Getting Starte
 Share  Tweet
fastai, ResNet

To leave a comment for the author, please follow the link and comment on their blog:
Full list of co
tuxette-chix » R.
R-bloggers.com o�ers daily e-mail updates about R news and tutorials about learning R and Archives
many other topics. Click here if you're looking to post or �nd an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. Select Mont

Other sit
← Previous post Next post →
SAS blogs
Jobs for R-use

Copyright © 2020 | MH Corporate basic by MH Themes

5 of 5 12/4/20, 2:21 PM

You might also like