我想在vb.net中运行一个r脚本,它将数据保存在.csv文件中。直到现在我发现了以下方法:
dim strCmd as String
strCmd = "R CMD BATCH" + "C:\test.R"
process.start("CMD.exe", strCmd
显然这应该可以工作,但在我的情况下,cmd弹出(在我的调试文件夹中lokated)并且没有任何反应。
我尝试的另一种方式是
process.start("Rgui.exe", "C:\test.R")
错误消息:参数“C:\ test.R”忽略
这也不起作用。
我的r脚本我只是用了一个例子
sink()
setwd("C:/")
x <- data.frame(a = I("a \" quote"), b = pi)
sink(test.csv)
答案 0 :(得分:6)
这对我有用:
Dim myprocess As New Process
myprocess.StartInfo = New ProcessStartInfo("C:\Program Files (x86)\R\R-2.6.2\bin\R.exe", "CMD BATCH C:/Users/test/test3.R C:/Users/test/testout.csv")
myprocess.Start()
第二种方法(第一个app。并没有给我一个好的csv输出,所以这里是一个解决方法):
Dim proc = New Process
proc.StartInfo.FileName = "C:\Program Files (x86)\R\R-2.6.2\bin\Rscript.exe"
proc.StartInfo.WorkingDirectory = "C:\Program Files (x86)\R\R-2.6.2\bin"
proc.StartInfo.Arguments = "C:/Users/Desktop/RtoVB/test4.r"
proc.StartInfo.UseShellExecute = True
proc.StartInfo.RedirectStandardOutput = False
proc.Start()
答案 1 :(得分:5)
这是我最近为此目的写的课程。您还可以传入和返回来自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();
proc.Close();
}
return result;
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
}