rcommand-line

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


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)?


Solution

  • 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".