我有一个C#程序生成一些R代码.现在我将脚本保存到文件,然后将其复制/粘贴到R控制台.我知道有一个到R的COM接口,但它似乎不适用于最新版本的R(或2.7.8之后的任何版本).有没有什么方法可以在将其保存到文件后以编程方式从C#执行R脚本?
这是我最近为此目的写的课程.您还可以从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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您对清理过程感兴趣,可能需要将以下内容添加到代码中.
proc.CloseMainWindow(); proc.Close();
小智 7
要做到这一点,C#
你需要使用
shell (R CMD BATCH myRprogram.R)
Run Code Online (Sandbox Code Playgroud)
一定要像这样包裹你的情节
pdf(file="myoutput.pdf")
plot (x,y)
dev.off()
Run Code Online (Sandbox Code Playgroud)
或图像包装