在Windows命令行中运行R代码

30

我有一些 R 代码储存在一个名为 analyse.r 的文件中。我想要从命令行(CMD)中运行该文件中的代码,而不必经过 R 终端,并且我还想能够传递参数并在我的代码中使用这些参数,类似于以下的伪代码:

C:\>(execute r script) analyse.r C:\file.txt

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

我该如何实现这个?

4个回答

36
  1. 你需要 Rscript.exe

  2. 你可以通过脚本控制输出,可以查看 sink() 及其文档。

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

  4. 你可以使用 getoptoptparse 包更精细地控制命令行参数。

  5. 如果其他方法均失败,请考虑阅读 手册贡献的文档


2
现在,docopt包可能是最好的选项解析器。 - user4117783
有没有可能发布一个Rscript.exe的下载链接。我查了几个地方都找不到。 - scs
1
在您的 R 安装的其他二进制文件所在的位置查找它。 - Dirk Eddelbuettel

7

确定 R 软件的安装路径。在 Windows 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

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

组成一个名为“a.R”的R文件,其内容为

#!/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 a.R /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
  Rscript a.R /home/impadmin/test.csv rows 2 

提供

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

这个函数将打印出通过命令行传递的索引指定的行的总和。

我们还可以按照以下方式将R脚本设置为可执行文件(在Linux上)。

 chmod a+x a.R

然后再次运行第二个示例,如下:

   ./a.R /home/impadmin/test.csv rows 2

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

0

将以下内容保存到文本文件中

f1 <- function(x,y){
print (x)
print (y)
}
args = commandArgs(trailingOnly=TRUE)
f1(args[1], args[2])

请在 Windows 命令提示符中运行以下命令

Rscript.exe path_to_file "hello" "world"

这将打印以下内容

[1] "hello"
[1] "world"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接