![](/img/trans.png)
[英]How to acess an R project (RTVS) from a C# project in VS 2017 with RDotNet?
[英]RDotNet vs R scripting
什么是使用RDotNet進行統計計算而不是生成R腳本文本文件並使用例如Process.Start從應用程序運行它的優勢/劣勢? 或者還有其他更好的方法嗎?
我需要執行大量命令,並且感覺將它們逐個發送到R需要花費很多時間。
我會說以下兩個場景是陳規定型的:
使用Process.Start,您將啟動一個新的R會話。 這可能需要一些時間,特別是如果您在腳本中使用需要加載的不同包。
如果您使用R.NET,您可以創建一個R實例,並繼續與它交談。 因此,如果您已經創建了一個Web服務來連接R和ASP,那么您不希望一直啟動R,因為這將非常耗費時間。 您只需要一次,就可以交互式地使用它。
R.NET目前可以啟動一次。 並行執行會有問題。
建議使用RScript。
我們的解決方案基於stackoverflow上的這個答案從.net調用R(編程語言)
隨着monor更改,我們從字符串發送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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.