什么时候使用 RDotNet 进行统计计算而不是生成 R 脚本文本文件并使用 Process.Start 从应用程序运行它是一种优势/劣势?还是有其他更好的方法?
我需要执行大量的命令,并且感觉将它们一个一个发送到 R 需要很多时间。
我想说以下两种情况是陈规定型的:
R.NET 目前可以初始化一次。并行执行会有问题。
建议使用 RScript。
我们的解决方案基于来自.net的stackoverflow Call R(编程语言)的答案
通过单声道更改,我们从字符串发送 R 代码并将其保存到临时文件,因为用户在需要时运行自定义 R 代码。
public static void RunFromCmd(string batch, params string[] args)
{
// Not required. But our R scripts use allmost all CPU resources if run multiple instances
lock (typeof(REngineRunner))
{
string file = string.Empty;
string result = string.Empty;
try
{
// Save R code to temp file
file = TempFileHelper.CreateTmpFile();
using (var streamWriter = new StreamWriter(new FileStream(file, FileMode.Open, FileAccess.Write)))
{
streamWriter.Write(batch);
}
// Get path to R
var rCore = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core") ??
Registry.CurrentUser.OpenSubKey(@"SOFTWARE\R-core");
var is64Bit = Environment.Is64BitProcess;
if (rCore != null)
{
var r = rCore.OpenSubKey(is64Bit ? "R64" : "R");
var installPath = (string)r.GetValue("InstallPath");
var binPath = Path.Combine(installPath, "bin");
binPath = Path.Combine(binPath, is64Bit ? "x64" : "i386");
binPath = Path.Combine(binPath, "Rscript");
string strCmdLine = @"/c """ + binPath + @""" " + file;
if (args.Any())
{
strCmdLine += " " + string.Join(" ", args);
}
var info = new ProcessStartInfo("cmd", strCmdLine);
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();
}
}
else
{
result += "R-Core not found in registry";
}
Console.WriteLine(result);
}
catch (Exception ex)
{
throw new Exception("R failed to compute. Output: " + result, ex);
}
finally
{
if (!string.IsNullOrWhiteSpace(file))
{
TempFileHelper.DeleteTmpFile(file, false);
}
}
}
}
完整的博文:http: //kostylizm.blogspot.ru/2014/05/run-r-code-from-c-sharp.html
使用 Process.Start 您将启动一个新的 R 会话。这可能需要一些时间,尤其是当您在脚本中使用需要加载的不同包时。
如果你使用 R.NET,你可以创建一个 R 实例,并继续与之对话。因此,如果您创建了一个将 R 与 ASP 连接起来的 Web 服务,您就不想一直启动 R,因为这将非常耗时。您只需要它一次,就可以交互式地使用它。