【发布时间】:2016-01-17 18:08:09
【问题描述】:
我有一个简单的 R 脚本,它接受输入值并根据输入值进行一些计算并将其写入 csv 文件。下面是我的 r 脚本的代码。
testfun=function(x){
x<-args[1]
x=sqrt(x)+(x*x)
a=x+x+x
b=data.frame(x,a)
setwd("D:\\R Script")
write.csv(b,"testfun.csv",row.names=F)
}
我使用 Jake Drew 提供的 Rscriptrunner 从我的 asp.net Web 应用程序调用此 rscript
/// <summary>
/// This class runs R code from a file using the console.
/// </summary>
public class RScriptRunner
{
/// <summary>
/// Runs an R script from a file using Rscript.exe.
/// Example:
/// RScriptRunner.RunFromCmd(curDirectory + @"\ImageClustering.r", "rscript.exe", curDirectory.Replace('\\','/'));
/// Getting args passed from C# using R:
/// args = commandArgs(trailingOnly = TRUE)
/// print(args[1]);
/// </summary>
/// <param name="rCodeFilePath">File where your R code is located.</param>
/// <param name="rScriptExecutablePath">Usually only requires "rscript.exe"</param>
/// <param name="args">Multiple R args can be seperated by spaces.</param>
/// <returns>Returns a string with the R responses.</returns>
public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath, string args, int iInput)
{
string file = rCodeFilePath;
string result = string.Empty;
try
{
var info = new ProcessStartInfo();
info.FileName = rScriptExecutablePath;
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
info.Arguments = rCodeFilePath + " " + args;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
using (var proc = new Process())
{
proc.StartInfo = info;
proc.Start();
result = proc.StandardOutput.ReadToEnd();
proc.Close();
}
return result;
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
}
我调用脚本到 rscriptrunner 的方式如下
int x = 64;
string scriptPath = string.Format(@"C:\Program Files\R\{0}\bin\Rscript.exe", Rversion);
string path = string.Format(@"D:\testfun.r");
string result = RScriptRunner.RunFromCmd(path, scriptPath, path.Replace('\\', '/'), x);
基本上我想将我的 Web 应用程序中的 x 值提供到我的 r 代码中,并在 r 脚本中指定的 csv 文件中获取输出。
我尝试了以下线程中提供的几种方法
How can I read command line parameters from an R script?
Run R script with start.process in .net
但是我无法得到我想要的。脚本没有被执行。 我还尝试在我的 rscript 中添加 args
基本上,我是一名 .net 开发人员,由于某些客户需要,我想从我的 Web 应用程序运行 r 脚本。我不太了解 R,如果有人帮助我了解如何将参数值传递给我的 r 代码,那对我会有帮助。
【问题讨论】:
-
这是你的整个 R 代码吗?您正在定义函数但从不使用它。
-
是的。执行上述代码后,该函数将被称为 testfun(x value)。