我有一个生成一些R代码的C#程序。现在我将脚本保存到文件,然后将其复制/粘贴到R控制台。我知道有一个到R的COM接口,但它似乎不适用于最新版本的R(或2.7.8之后的任何版本)。有什么方法可以在将其保存到文件后以编程方式从C#执行R脚本吗?
答案 0 :(得分:9)
这是我最近为此目的写的课程。您还可以传入和返回来自C#和R的参数:
/// <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)
{
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();
}
return result;
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
}
注意:如果您有兴趣清理整个过程,可能需要在代码中添加以下内容。
proc.CloseMainWindow(); proc.Close();
答案 1 :(得分:7)
要在C#
执行此操作,您需要使用
shell (R CMD BATCH myRprogram.R)
请务必像这样包装你的情节
pdf(file="myoutput.pdf")
plot (x,y)
dev.off()
或图像包装
答案 2 :(得分:2)
我认为C#具有类似于system()
的功能,允许您调用通过Rscript.exe
运行的脚本。
答案 3 :(得分:1)
我们的解决方案基于stackoverflow上的这个答案Call R (programming language) from .net
随着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
答案 4 :(得分:1)
这是实现这一目标的简单方法,
我的Rscript位于:
C:\ Program Files \ R \ R-3.3.1 \ bin \ RScript.exe
R代码位于:
C:\ Users \用户联想\桌面\ R_trial \ withoutALL.R
using System;
using System.Diagnostics;
public partial class Rscript_runner : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Process.Start(@"C:\Program Files\R\R-3.3.1\bin\RScript.exe","C:\\Users\\lenovo\\Desktop\\R_trial\\withoutALL.R");
}
}