2016-11-17 59 views
0

我有一个调用R脚本的批处理文件。它工作正常。我需要知道如何从Windows中的批处理文件调用R脚本中的函数?如何用参数调用此函数:从批处理文件中调用R脚本中的函数

PNLCalcMultipleDatesClient("2010-10-03", "2010-10-05", "XYZ") 

此命令行工作,但它没有R脚本中的函数调用。你能帮我在Windows中修改这个命令行并调用上面的函数吗?

"\\C1PRDTLS01.axinc.com\Dev\RiskClient\inputCData\PNLCalculation\R\R-3.1.1\bin\R.exe" CMD BATCH --no-save --no-restore "\\C1PRDTLS01.axinc.com\Dev\RiskClient\inputCData\PNLCalculation\RScript\RadarPNLTimeseries.R" 

这里是R脚本:

PNLCalcMultipleDatesClient("2010-10-03", "2010-10-05", "Dunavant") 

PNLCalcMultipleDatesClient <- function(begindate, enddate, Client) 
{ 
    # Do some operation here.... 
    ..... 
    ...... 

} 

回答

1

下面是一个例子。这里是我的Rscript,我倾向于将它们保存为txt本身。

## Rscript: Passing arguments to the Rscripts likes args[i] 
#!/usr/bin/env Rscript 
args = commandArgs(trailingOnly=TRUE) 
print(1:args[1]) 
df=data.frame(1:args[1]) 
write.csv(df, args[2]) 

然后你的批处理文件看起来像这样。然后,将这些参数直接提供给cmd或从中创建批处理文件。

echo off 
Rscript rparam.txt 1000 out.csv 

对于你的情况,你的RSCRIPT(R_with_par.R)将是:

#!/usr/bin/env Rscript 
args = commandArgs(trailingOnly=TRUE) 
x1=args[1] 
x2=args[2] 
x3=args[3] 
PNLCalcMultipleDatesClient <- function(begindate, enddate, Client) 
{ 
    # Do some operation here.... 
    ..... 
    ...... 

} 

PNLCalcMultipleDatesClient(as.Date(x1), as.Date(x2), as.character(x3)) 

而且你的CMD命令是:

Rscript R_with_par.R 2010-10-03 2010-10-05 Dunavant 

你必须确保参数你传递的格式是R所要求的格式。如果你不在同一个目录中,给出R脚本的路径。 Rscript也比R CMD好得多。

+0

谢谢。我知道如何调用R脚本。我的问题是如何从命令行调用R脚本中的函数。有什么办法可以做到吗?或者任何主函数或R中存在的自动调用Java或C#的东西? – Partha

+0

我不认为你可以从cmd调用r函数。你需要把这个函数放在R脚本中,然后调用它。 –

+0

在这种情况下,如何将参数传递给该函数?比方说,在我的R脚本中,我有几个函数functionA(arg1,arg2),functionB(arg1,arg2)等。如果我从cmd传递这些参数,R脚本将如何理解要传递哪个函数? – Partha

相关问题