R之批处理

在linux下如何编写脚本调用R语言写的程序呢?

R语言进行批处理有2种方式:

  • R CMD BATCH --options scriptfile outputfile
  • Rscript --options scriptfile arg1 arg2 arg3 >outputfile

options的选项以及含义如下:

  • --slave          类似于--quiet,它禁止回送输入的信息,使R软件输出的信息更为简洁。
  • --no-restore 在R启动时不还原工作空间。对于希望以空白工作空间启动R的脚本而言,这个选项很有必要。
  • --no-save     在退出R时,不保存工作空间;否则,R会保存当前工作空间并覆盖原有工作目录中的.RData文件。
  • --no-init-file  不读取.Rprofile文件或者~/. Rprofile文件。

1. R CMD BATCH的用法

这种最基本的知识,不多说,直接上例子:

    clotting <- data.frame(
        u = c(5,10,15,20,30,40,60,80,100),
        lot1 = c(118,58,42,35,27,25,21,19,18),
        lot2 = c(69,35,26,21,18,16,13,12,12))
    cat("Model data:\n")
    print(clotting)
    warning("Model starting")
    obj <- glm(lot1 ~ log(u), data=clotting, family=Gamma)
    cat("\nEstimated parameters:\n")
    coef(summary(obj))
    q(runLast=FALSE)

注:代码最后的是不让程序打印proc.time函数的输出结果。

上述的命令保存成test.R,在命令行中通过下面的命令进行调用:

> R CMD BATCH --slave test.R out

out文件中的输出结果为:

Model data:
    u lot1 lot2
1   5  118   69
2  10   58   35
3  15   42   26
4  20   35   21
5  30   27   18
6  40   25   16
7  60   21   13
8  80   19   12
9 100   18   12
警告信息:
Model starting 

Estimated parameters:
               Estimate   Std. Error   t value     Pr(>|t|)
(Intercept) -0.01655438 0.0009275466 -17.84749 4.279149e-07
log(u)       0.01534311 0.0004149596  36.97496 2.751191e-09

2. Rscript 用法

     与上述方法不同的是,Rscript可以传入参数,其中options的选项取值是相同的。下面的例子是写在arith.R文件中,通过argv<-commandArgs(TRUE)来将传递的参数转化为字符串数组。

argv<-commandArgs(TRUE)
x<-as.numeric(argv[1])
y<-as.numeric(argv[2])
cat("x=",x,"\n")
cat("y=",y,"\n")
cat("x+y=",x+y,"\n")
cat("x^y",x^y,"\n")

调用的命令:

> Rscript arith.R  1 2 >output

输出结果:

x= 1 
y= 2 
x+y= 3 
x^y 1 

也可以将arith.R改成可执行文件在命令行中直接执行:

#! /usr/bin/Rscript --slave
library(MASS)
argv<-commandArgs(TRUE)
x<-as.numeric(argv[1])
y<-as.numeric(argv[2])
cat("x=",x,"\n")
cat("y=",y,"\n")
cat("x+y=",x+y,"\n")
cat("x^y",x^y,"\n")
write.matrix(matrix(1:x,nrow=y),file="m.txt",sep=" ")

注:如果R语言中用到了其他的包,则在文件中加入相应的包名即可。

在命令行中修改arith.R为可执行文件:

> chmod +x arith.R
> ./arith.R 10 2

输出结果:

x= 1 
y= 2 
x+y= 3 
x^y 1 

 m.txt文件中数据为:

 1  3  5  7  9
 2  4  6  8 10

 

参考文章:

1. http://blog.revolutionanalytics.com/2009/06/running-scripts-with-r-cmd-batch.html

2. http://book.2cto.com/201305/21969.html

 

posted @ 2015-05-20 15:59  很厉害的名字  阅读(2708)  评论(0编辑  收藏  举报