是否可以在OSX上以Mono或.NET从Unity C#运行R代码?

有没有办法在Mono中使用Unity的C#运行R脚本?

如果没有办法使用Mono运行R脚本,我愿意使用.NET

更新

因此,以下代码将调用R脚本,但如果从unity monodevelop调用则不会输出文件。 将字符串返回到mono是可以的,但是在startInfo.UseShellExecute和startInfo.RedirectStandardOutput上更改true和false会引发错误。 以下是将调用R代码的C#代码:

System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "Rscript"; startInfo.WorkingDirectory = Application.dataPath + "/myUnity/Scripts/"; startInfo.Arguments = "Rexp1.R"; startInfo.CreateNoWindow = true; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.UseShellExecute = true; startInfo.RedirectStandardOutput = false; process.StartInfo = startInfo; process.Start(); 

我确信R脚本会输出一个文件,或者我可以抓住stdout并保持它。 我将很高兴输出到文件或具有统一允许返回的字符串是R脚本的输出。

更新2 * – 这是R脚本。

 sink("output.txt") nts <- matrix(rnorm(100), nrow = 500) ds <- dist(nts,method = "euclidean", diag = TRUE, upper=TRUE) dm <- as.matrix(ds) # distance matrix print(dm) sink() 

只需从您所做的事情中读取流程的输出。

我没有MAC计算机,但应该是一样的。 请参阅代码中的注释。

您的R脚本在我的机器上有错误,因此它输出到stderr而不是stdout。

 using UnityEngine; public class RunR : MonoBehaviour { void Start () { System.Diagnostics.Process process = new System.Diagnostics.Process(); // For macOS, here should be // I. "/bin/sh" // II. "path_of_the_Rscript" process.StartInfo.FileName = @"E:\Program Files\R\R-3.3.2\bin\x64\Rscript.exe"; // For macOS, here should be // I. "-c path_of_the_Rscript Rexp1.R" if "/bin/sh" is used // II. "Rexp1.R" if "path_of_the_Rscript" is used process.StartInfo.Arguments = "Rexp1.R"; process.StartInfo.WorkingDirectory = Application.dataPath; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); //read the output string output = process.StandardOutput.ReadToEnd(); string err = process.StandardError.ReadToEnd(); process.WaitForExit(); Debug.Log(output); Debug.LogError(err); } } 

输出继电器:

输出继电器

注意项目视图。 有一个Rexp1.R和一个RunR.cs 第一个输出是Object ,因为stdout没有输出,因此输出为null。

在我将Rexp1.R的内容更改为以下内容之后,

 print("12345") print("ABCDE") 

控制台视图中的输出变为:

正常输出

更新:

安装igraph包并删除sink("output.txt")和最后一个sink() ,输出为:

可能正确的输出