Is it possible to pipe code to R or Rscript in commandline?
Asked Answered
C

2

5

for example, test.R is a one line file:

$ cat test.R  
# print('Hello, world!')

we can run this file by Rscript test.R or R CMD BATCH test.R. However, is it possible to instruct R to execute code piped to it, something like cat test.R | Rscript or cat test.R | R CMD BATCH (both doesn't work)?

Comfrey answered 21/3, 2017 at 14:22 Comment(0)
L
9

Rscript will not listen to stdin:

$ echo "2 + 2" | Rscript

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

--options accepted are
  --help              Print usage and exit
  --version           Print version and exit
  --verbose           Print information on progress
  --default-packages=list
                      Where 'list' is a comma-separated set
                        of package names, or 'NULL'
or options to R, in addition to --slave --no-restore, such as
  --save              Do save workspace at the end of the session
  --no-environ        Don't read the site and user environment files
  --no-site-file      Don't read the site-wide Rprofile
  --no-init-file      Don't read the user R profile
  --restore           Do restore previously saved objects at startup
  --vanilla           Combine --no-save, --no-restore, --no-site-file
                        --no-init-file and --no-environ

'file' may contain spaces but not shell metacharacters
Expressions (one or more '-e <expr>') may be used *instead* of 'file'
See also  ?Rscript  from within R
$

But littler has been doing this just fine as it was built for this (and more):

$ echo "2 + 2" | r -p                # -p switch needed for print
[1] 4
$ echo "print(2 + 2)" | r 
[1] 4
$ 

Note that operations are by default "silent" either explicit print() statements or the -p flag are your friend.

For completeness, R can now do it too but I forget when it was added:

$ echo "2 + 2" | R --slave
[1] 4
$ 

I have an older blog post comparing the start-up speeds, so my money is still on littler for these things -- and I have numerous scripts and cron jobs using it as it "just works".

Logrolling answered 21/3, 2017 at 14:31 Comment(4)
I installed your littler package inside R, and added r to my ~/.bashrc with alias. It worked nicely!Comfrey
Out of curiousity, by the alias? To get the binary from the installed package? I usually just softlink to /usr/local/bin.Logrolling
the package is installed to ~/R/x86_64-pc-linux-gnu-library/3.3/littler/bin/r by default. In case we don't have write access in /usr/local/bin, I think it is easier to change .bashrc.Comfrey
Quite right. If you can't sudo then that is all you get, sadly.Logrolling
L
0

You can do echo "print('hello world')" | Rscript --slave -

Lashundalasker answered 12/10 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.