Hatshepsut
Hatshepsut

Reputation: 6652

Run R command from command line

Is there a way to run an R command from the command line? Something like

$ R --run '1+1'
2

or even like

$ Rscript < '1+1'
2

Upvotes: 21

Views: 13031

Answers (3)

mt1022
mt1022

Reputation: 17289

With littler package installed and the path of r properly configured, you can do something like this:

echo 'print(1+1)' | r  
# [1] 2

Note, r is not a typo. It is a command from littler. It also support the -e option like R and Rscript:

r -e 'print(1+1)'     
# [1] 2

It seems that it only prints when you call print/cat/... explicitly in expression.

Upvotes: 2

Hatshepsut
Hatshepsut

Reputation: 6652

You can do it with the R command:

$ R --slave -e '1+1'
[1] 2

From man R:

   --slave
          Make R run as quietly as possible

   -e EXPR
          Execute 'EXPR' and exit

Upvotes: 14

Andrey Shabalin
Andrey Shabalin

Reputation: 4614

The command line option -e does exactly that.

Rscript.exe -e "1+1"

[1] 2

It is clearly explained in the help which you get if you just run RScript without parameters:

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

Upvotes: 18

Related Questions