从命令行运行 R 脚本 [英] Run R script from command line

查看:48
本文介绍了从命令行运行 R 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 a.r 的文件,它的 chmod 为 755,

I have a file, called a.r, it has a chmod of 755,

sayHello <- function(){
   print('hello')
}

sayHello()

如何通过命令行运行它?

How can I run this via command-line?

推荐答案

如果你想让输出打印到终端最好使用 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.

这篇关于从命令行运行 R 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆