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

Cod*_*oss 6 c# macos r monodevelop unity-game-engine

有没有办法在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();
Run Code Online (Sandbox Code Playgroud)

我确定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()
Run Code Online (Sandbox Code Playgroud)

zwc*_*oud 4

只需像您所做的那样从过程的输出中读取即可。

我没有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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

输出

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

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

print("12345")
print("ABCDE")
Run Code Online (Sandbox Code Playgroud)

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

正常输出

更新:

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

可能的正确输出

  • 对于那些尝试通过 Unity 运行 R 代码时偶然发现此答案的人来说,只是一个旁注。这里的方法可用于运行 python、C、C++ 或任意数量的其他编程语言脚本。这是一个非常有用的跨平台(OSX 或 Windows)解决方案。 (2认同)