我有一些 R 代码储存在一个名为 analyse.r 的文件中。我想要从命令行(CMD)中运行该文件中的代码,而不必经过 R 终端,并且我还想能够传递参数并在我的代码中使用这些参数,类似于以下的伪代码:
C:\>(execute r script) analyse.r C:\file.txt
执行此脚本并将 "C:\file.txt" 作为参数传递给脚本,然后可以使用它进行进一步处理。
我该如何实现这个?
我有一些 R 代码储存在一个名为 analyse.r 的文件中。我想要从命令行(CMD)中运行该文件中的代码,而不必经过 R 终端,并且我还想能够传递参数并在我的代码中使用这些参数,类似于以下的伪代码:
C:\>(execute r script) analyse.r C:\file.txt
执行此脚本并将 "C:\file.txt" 作为参数传递给脚本,然后可以使用它进行进一步处理。
我该如何实现这个?
确定 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
有两种方法可以从命令行(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)
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
将以下内容保存到文本文件中
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"
docopt
包可能是最好的选项解析器。 - user4117783