Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

r - 从命令行运行R脚本(Run R script from command line)

I have a file, called ar , it has a chmod of 755,

(我有一个名为ar的文件,它的chmod为755,)

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

sayHello()

How can I run this via command-line?

(如何通过命令行运行它?)

  ask by Sait translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(如果要将输出打印到终端,最好使用Rscript)

Rscript a.R

Note that when using R CMD BATCH aR 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 aR ,将创建一个名为a.Rout的新文件,而不是将输出重定向到标准输出并在终端上显示。)

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

One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion.

(使用Rscript时要注意的另一件事是,它默认情况下不会加载methods包,这可能会引起混乱。)

So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

(因此,如果您依赖方法提供的任何内容,则需要在脚本中显式加载它。)

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

(如果您真的想使用./aR方式调用脚本,则可以添加一个适当的#!)

to the top of the script

(到脚本顶部)

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

sayHello()

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.

(我还将注意到,如果您在* unix系统上运行,则有一个有用的littler软件包,该软件包可为R提供简单的命令行管道。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...