从命令行运行R代码(Windows)

Ext*_*der 23 windows command-line r

我在一个名为analyse.r的文件中有一些R代码.我希望能够从命令行(CMD)运行该文件中的代码,而不必通过R终端,我也希望能够传递参数并在我的代码中使用这些参数,像下面的伪代码:

C:\>(execute r script) analyse.r C:\file.txt
Run Code Online (Sandbox Code Playgroud)

这将执行脚本并将"C:\ file.txt"作为参数传递给脚本,然后它可以使用它对它进行一些进一步的处理.

我该如何做到这一点?

Dir*_*tel 30

  1. 你想要的Rscript.exe.

  2. 您可以在脚本中控制输出 - 请参阅sink()及其文档.

  3. 您可以通过访问命令参数commandArgs().

  4. 您可以通过getoptoptparse包更精细地控制命令行参数.

  5. 如果其他一切都失败了,请考虑阅读手册提供的文档

  • 现在,`docopt` 包可能是最好的选项解析器。 (2认同)

rup*_*ali 5

有两种方法可以从命令行(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)
Run Code Online (Sandbox Code Playgroud)

在 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 a.R /home/impadmin/test.csv rows 2 
Run Code Online (Sandbox Code Playgroud)

you passed the following at the command line
    /home/impadmin/test.csv rows 2
Matrix is:
      x1 x2
    1  1  2
    2  3  4
    3  5  6
    4  7  8
Dimensions of the matrix are
    4 2
Run Code Online (Sandbox Code Playgroud)

此函数将打印其索引从命令行处理传递的行的总和...行总和 7

我们还可以使 R 脚本可执行如下(在 linux 上)

 chmod a+x a.R
Run Code Online (Sandbox Code Playgroud)

并再次运行第二个示例

   ./a.R /home/impadmin/test.csv rows 2
Run Code Online (Sandbox Code Playgroud)

这也适用于 Windows 命令提示符..


小智 5

确定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
Run Code Online (Sandbox Code Playgroud)