且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从命令行运行 R 脚本

更新时间:2022-12-31 11:07:51

如果你想让输出打印到终端***使用 Rscript

If you want the output to print to the terminal it is best to use Rscript

Rscript a.R

请注意,当使用 R CMD BATCH a.R 时,将创建一个名为 a.Rout 的新文件,而不是将输出重定向到标准输出并在终端上显示.

Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

R CMD BATCH a.R
# Check the output
cat a.Rout

使用 Rscript 需要注意的另一件事是默认情况下它不会加载 methods 包,这会导致混淆.因此,如果您依赖方法提供的任何内容,则需要在脚本中显式加载它.

One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

如果你真的想使用 ./a.R 方式来调用脚本,你可以在脚本的顶部添加一个合适的 #!

If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

#!/usr/bin/env Rscript
sayHello <- function(){
   print('hello')
}

sayHello()

我还要注意,如果您在 *unix 系统上运行,则有一个有用的 littler 包,它为 R 提供简单的命令行管道.可能需要使用 littler 通过脚本运行闪亮的应用程序?可以在本问题中找到更多详细信息.

I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.