Executing packages as scripts

In python I can run module code as a script, for example, python -m mymodule_main -a 1 -b 2. Is there any way to do something like this in R? I am using optparse to handle arguments in my scripts so it would be great to use it in this possible solution too.

I am not 100% sure I understand your question, but in R you can use command line tool Rscript mymodule.R to execute your code from command line (assuming mymodule.R is your script file).

This will have implications - your code will run in default directory, so you need to use setwd() or use absolute filenames in any objects you use - but it is very handy; for example when setting up regular reporting via CRON jobs.

I know about Rscript, that ,however, is external solution (actually what I am doing now). I would like something I can keep inside the same package repository. i.e.


and then I could run something like myscript.R -a 1-b 2. I guess I could put the script folder of the package in the $PATH but that will be tedious to maintain I think. In the python case, the script that you run (with arguments) is really part of the package so it is updated every time you reinstall the package.

I knew it was a cheap shot. I am afraid I know too little about python package development to relate fully to your problem.

I wish you luck, and I hope you will find someone more knowledgeable than me to help you out.


You can put scripts in exec/ and they will be installed along with your package. If you want to call the script from anywhere I would create a small shell script to do so (say it is called myscript)


Rscript -e 'source(file = system.file("exec/script.R", package = "mypkg")' $@

Then you can put this in your ~/bin or somewhere else on your PATH, and run it regardless of where your R package is installed. Command line arguments will be passed to your package's script by the $@ variable in the shell script, so they can be used by optparse.


That would be actually really useful, thanks for the tip!