1

In python we can run a python code:

python -c "import os;print(os.listdir('./'))"

My question is simple, how can we do a similar code execution of Rscript without opening R shell or writing a R script?

Something like :

Rscript -c "installed.packages()[,'Package']"
Amit Tripathi
  • 7,003
  • 6
  • 32
  • 58
  • 1
    A discussion about `littler` vs `Rscript` is here: http://stackoverflow.com/questions/3205302/difference-between-rscript-and-littler – Spacedman Apr 06 '16 at 14:53

2 Answers2

8

If you just type Rscript you get

Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]

...

Expressions (one or more '-e ') may be used instead of 'file'

Thus

Rscript -e "installed.packages()[,'Package']" 

Another possibility is

echo "installed.packages()[,'Package']" | R --slave

(a little slower but more robust because it does things like load the methods package)

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • I just asked you a couple of days ago why you would use `| R --slave`. Care to expand? – Dirk Eddelbuettel Apr 06 '16 at 14:46
  • If I didn't have littler and I wanted to do something that required the `methods` package and I didn't want to use one of the other workarounds (explicitly add `library("methods")` or [set R_DEFAULT_PACKAGES](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html). I've noticed R-core members using this idiom (not that that necessarily makes it right). – Ben Bolker Apr 06 '16 at 15:33
  • On the other hand, it may be that littler works everywhere that Rscript would anyway (I don't know what " only supported on systems with the execv system call" implies practically about Rscript's restrictions) – Ben Bolker Apr 06 '16 at 15:34
  • In an answer to the linked question from @spacedman you say "Rscript is now everywhere where R is", so provided littler is still non-Windows, `R --slave` might be a reasonable alternative to Rscript – Ben Bolker Apr 06 '16 at 15:36
4

There's littler for this, which manifests itself as an r command:

$ r -pe 'sqrt(2)'
[1] 1.414214

And the actual question can be answered thusly:

$ r -e'IP <- installed.packages(); print(head(IP[,"Package"]))'
    docopt   magrittr    stringi    stringr    littler       base 
  "docopt" "magrittr"  "stringi"  "stringr"  "littler"     "base" 
Spacedman
  • 92,590
  • 12
  • 140
  • 224