我在一个名为analyse.r的文件里面有一些R代码。 我希望能够从命令行(CMD),运行该文件中的代码,而不必通过Rterminal,我也想能够传递参数,并在我的代码中使用这些参数,东西像下面的伪代码一样:
C:\>(execute r script) analyse.r C:\file.txt
这将执行脚本并将“C:\ file.txt”作为parameter passing给脚本,然后可以使用它对脚本做进一步的处理。
我如何做到这一点?
你想要Rscript.exe
。
您可以控制脚本内的输出 – 请参阅sink()
及其文档。
你可以通过commandArgs()
来访问命令参数。
您可以通过getopt和optparse包更精细地控制命令行参数。
如果一切都失败了,请考虑阅读手册或贡献文档
有两种方法从命令行(Windows或Linux shell)运行R脚本。
1)R CMD方式R CMD BATCH后跟R脚本名称。 这个输出也可以根据需要传送给其他文件。
然而,这种方式是有点老,使用Rscript越来越流行。
2)Rscript方式(所有平台都支持这种方式,下面的例子只针对Linux进行测试)这个例子涉及到csv文件的路径,csv文件的函数名和属性(行或列)索引功能应该工作。
test.csv文件的内容x1,x2 1,2 3,4 5,6 7,8
创建一个R文件“aR”,其内容是
#!/usr/bin/env Rscript cols <- function(y){ cat("This function will print sum of the column whose index is passed from commandline\n") cat("processing...column sums\n") su<-sum(data[,y]) cat(su) cat("\n") } rows <- function(y){ cat("This function will print sum of the row whose index is passed from commandline\n") cat("processing...row sums\n") su<-sum(data[y,]) cat(su) cat("\n") } #calling a function based on its name from commandline … y is the row or column index FUN <- function(run_func,y){ switch(run_func, rows=rows(as.numeric(y)), cols=cols(as.numeric(y)), stop("Enter something that switches me!") ) } args <- commandArgs(TRUE) cat("you passed the following at the command line\n") cat(args);cat("\n") filename<-args[1] func_name<-args[2] attr_index<-args[3] data<-read.csv(filename,header=T) cat("Matrix is:\n") print(data) cat("Dimensions of the matrix are\n") cat(dim(data)) cat("\n") FUN(func_name,attr_index)
在Linux shell上运行下面的命令:Rscript aR /home/impadmin/test.csv cols 1在命令行中给出以下结果/home/impadmin/test.csv cols 1矩阵是:x1 x2 1 1 2 2 3 4 3 5 6 4 7 8矩阵的尺寸是4 2该函数将打印索引从命令行处理传递的列的总和…列总和16
在Linux shell Rscript aR /home/impadmin/test.csv第2行运行以下命令可以在命令行/home/impadmin/test.csv第2行中传递以下内容2矩阵是:x1 x2 1 1 2 2 3 4 3 5 6 4 7 8矩阵的尺寸是4 2这个函数将打印索引从命令行处理传递的行的总和…行总和7
我们还可以使R脚本可执行如下(在Linux上)chmod a + x aR并以./aR /home/impadmin/test.csv行2再次运行第二个示例
这应该也适用于Windows命令提示符。
确定R的安装位置。 对于窗口7,路径可能是
1.C:\Program Files\R\R-3.2.2\bin\x64> 2.Call the R code 3.C:\Program Files\R\R-3.2.2\bin\x64>\Rscript Rcode.r