从命令行运行R命令

时间:2017-08-22 04:48:40

标签: r command-line

有没有办法从命令行运行R命令?像

这样的东西
$ R --run '1+1'
2

甚至喜欢

$ Rscript < '1+1'
2

3 个答案:

答案 0 :(得分:7)

命令行选项-e就是这样做的。

Rscript.exe -e "1+1"

[1] 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

答案 1 :(得分:4)

您可以使用R命令执行此操作:

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

来自man R

   --slave
          Make R run as quietly as possible

   -e EXPR
          Execute 'EXPR' and exit

答案 2 :(得分:0)

安装littler package并正确配置r路径后,您可以执行以下操作:

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

注意,r不是拼写错误。这是来自littler的命令。它还支持-eR的{​​{1}}选项:

Rscript

它似乎只在您在表达式中明确调用r -e 'print(1+1)' # [1] 2 时打印。