2010-12-20 23 views
9

Mam program C#, który generuje kod R. Teraz zapisuję skrypt do pliku, a następnie kopiuję/wklejam go do konsoli R. Wiem, że istnieje interfejs COM dla R, ale nie wydaje się działać z najnowszą wersją R (lub jakiejkolwiek wersji po 2.7.8). Czy jest jakiś sposób po prostu programowo wykonać skrypt R z C# po zapisaniu go do pliku?Wykonywanie skryptu R programowo

Odpowiedz

6

Aby to zrobić w C# trzeba użyć

shell (R CMD BATCH myRprogram.R) 

należy owinąć działek jak ten

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

lub obraz owijarki

+0

Ok, więc teraz mam: filled.contour (...) savePlot ("heatmap1.png" type = "png") sugerujesz zmienić go na adres: PNG ("heatmap1. png ") filled.contour (...) dev.off() –

+0

To działało! Dziękuję Ci! –

+0

Jeśli masz kraty lub wykresy ggplot2, prawdopodobnie będziesz musiał użyć polecenia print() wokół instrukcji wydruku. –

2

Przypuszczam, że C# ma funkcję podobną do funkcji system(), która umożliwia wywoływanie skryptów uruchamianych przez Rscript.exe.

+0

Pomyślałem o tym, z wyjątkiem sytuacji, gdy uruchamiam skrypt za pomocą Rscript, to nie zapisuje poprawnie działek. Skrypt tworzy kolekcję map ciepła i zapisuje wykresy do różnych plików. Kiedy uruchamiam program Rscript, zapisuje on tylko ostatnie zdjęcie w pliku PDF zamiast osobnych plików png, które otrzymuję podczas wykonywania przez IDE. –

+1

W ten sposób R działa interaktywnie, a nie interaktywnie. Otwórz urządzenia, takie jak 'pdf()' lub 'png()' lub 'jpeg()' lub ... jawnie z argumentami nazw plików. –

+0

Myślałem, że to robię: savePlot ("heatmap1.png", type = "png"); –

1

nasze rozwiązanie oparte na tej odpowiedzi na stackoverflow Call R (programming language) from .net

Z mono r Zmień, wysyłamy kod R z ciągu i zapisujemy go do pliku tymczasowego, ponieważ użytkownik uruchamia niestandardowy kod R, gdy jest to konieczne.

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

Pełna blogu: http://kostylizm.blogspot.ru/2014/05/run-r-code-from-c-sharp.html

7

Oto klasa Niedawno napisałem do tego celu. Można również przejść i wrócić argumenty z C# i 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); 
      } 
    } 
} 

UWAGA: Możesz dodać następujący kod do Ciebie, jeśli jesteś zainteresowany czyszczeniem proces.

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

+0

Nie działa dla mnie i nie usuwa nowych wystąpień cmd * .exe - zobacz http://stackoverflow.com/questions/8559956/c-sharp-process-start-failed-to-dispose-thread-resources –

+0

Używam go cały czas. Prawdopodobnie masz problem z rScriptExecutablePath (proces może nie mieć dostępu do pełnej ścieżki exe lub musisz utworzyć zmienną środowiskową dla Rscript.exe), kod R, który próbujesz uruchomić (jeśli kod R zawodzi, zobaczysz brak wyników lub błąd) lub może brakować Rscript.exe. –

0

Oto prosty sposób, aby to osiągnąć,

My Rscript znajduje się pod adresem:

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

R Kod jest:

C: \ Users \ Lenovo \ pulpitu \ R_trial \ withoutALL.R

Powiązane problemy