以编程方式执行 R 脚本

发布于 2024-10-08 01:56:14 字数 144 浏览 0 评论 0原文

我有一个生成一些 R 代码的 C# 程序。现在,我将脚本保存到文件,然后将其复制/粘贴到 R 控制台中。我知道 R 有一个 COM 接口,但它似乎不适用于最新版本的 R(或 2.7.8 之后的任何版本)。有什么方法可以在将 R 脚本保存到文件后以编程方式从 C# 执行它吗?

I have a C# program that generates some R code. Right now I save the script to file and then copy/paste it into the R console. I know there is a COM interface to R, but it doesn't seem to work with the latest version of R (or any version after 2.7.8). Is there some way I can just programmatically execute the R script from C# after saving it to file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

红尘作伴 2024-10-15 01:56:19

我认为 C# 有一个类似于 system() 的函数,它允许您调用通过 Rscript.exe 运行的脚本。

I would presume that C# has a function similar to system() which would allow you to call scripts running via Rscript.exe.

[旋木] 2024-10-15 01:56:19

我们的解决方案基于 stackoverflow 上的这个答案 从 .net 调用 R(编程语言)

通过单一更改,我们从字符串发送 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

Our solution based on this answer on stackoverflow Call R (programming language) from .net

With monor change, we send R code from string and save it to temp file, since user run custom R code when needed.

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);
            }
        }
    }
}

Full blog post: http://kostylizm.blogspot.ru/2014/05/run-r-code-from-c-sharp.html

超可爱的懒熊 2024-10-15 01:56:18

要在 C# 中执行此操作,您需要使用

shell (R CMD BATCH myRprogram.R)

确保像这样包装您的绘图

pdf(file="myoutput.pdf")
plot (x,y)
dev.off()

或图像包装器

To do this in C# you'll need to use

shell (R CMD BATCH myRprogram.R)

Be sure to wrap your plots like this

pdf(file="myoutput.pdf")
plot (x,y)
dev.off()

or image wrappers

蒲公英的约定 2024-10-15 01:56:18

这是实现这一目标的简单方法,

我的 Rscript 位于:

C:\Program Files\R\R-3.3.1\bin\RScript.exe

R 代码位于:

C:\Users\lenovo\Desktop\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");
        }
            }

Here is a simple way to achieve that,

My Rscript is located at:

C:\Program Files\R\R-3.3.1\bin\RScript.exe

R Code is at :

C:\Users\lenovo\Desktop\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");
        }
            }
狼性发作 2024-10-15 01:56:16

这是我最近为此目的编写的课程。您还可以从 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();

Here is the class I recently wrote for this purpose. You can also pass in and return arguments from C# and 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);
            }
    }
}

NOTE: You may want to add the following to you code, if you are interested in cleaning up the process.

proc.CloseMainWindow();
proc.Close();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文