contract@chaoreumsoft.co.kr |    031-921-0523

R언어 C# 연동 방안

페이지 정보

작성자최고관리자

본문

dd6a48c56a0cfab7e3549831c0edc9aa_1591150438_4823.png
 

R언어란

통계 계산과 그래픽을 위한 프로그래밍 언어이다. 뉴질랜드의 로버트 잰틀맨과 로스 이하카가 개발하였다. 1993년 처음으로 공개되었다. R은 GPL 하에 배포되는 S 프로그래밍 언어의 구현으로 GNU S라고도 한다.


장점

* 오픈소스, 무료 소프트웨어

* 포괄적인 통계플랫폼 : 다양한 라이브러리, 다양한 분석기법, 정형/비정형

* 시각화 기능으로 수학 기호를 포함할 수 있는 출판물 수준의 그래프를 제공

* 웹 어플리케이션 개발 프레임워크인 Shiny의 고도화로 통계 또는 머신러닝 모델을 웹과 연동 가능


단점

* 통계 최적화를 위해 성능을 희생했다

* 인터프리터언어로서 R코드가 실행될때, 변경될 때마다 다시 해석하므로 비교적 느리다.

* 프로그램 자체의 한국어 기능을 제공하지 않는다. 


동작원리

R은 싱글스레드이므로 1개의 CPU코어만 사용한다. 멀티코어를 활용하려면 병렬프로그래밍 기법이 필요하다. 

dd6a48c56a0cfab7e3549831c0edc9aa_1591150873_4264.png
R은 R코드를 메인 메모리에 올려둔다. R 해석기는 R코드를 기계코드로 변환하고 기계코드로 CPU가 처리한다. 

인메모리에서 처리하기 때문에 빠르지만, 최대 데이터 크기는 사용가능한 RAM의 크기에 따라 달라진다. 


통합개발환경

통합 개발 환경으로 RStudio가 가장 무난하다. R 본체가 설치되어 있어야 작동하며, 훨씬 편리한 인터페이스를 제공하는 것이 강점. 단, 폴더 경로나 파일 이름에 한글이 들어가면 제대로 작동하지 않을 수 있으니 주의할 것. 특히 사용자 계정 이름이 한글일 경우 기본 폴더 경로 자체에 한글이 들어가게 되므로 제대로 실행되지 않는다. 이 경우 관리자 권한으로 실행시키면 된다. 


그 외의 IDE나 에디터들에는 다음이 있다. 보통 R에 대한 문법 검사와 코드 색상을 지원하는 플러그인 형태로 제공 

* ConTEXT

* Eclipse (StatET)

* Emacs (Emacs Speaks Statistics)

* LyX (modules for knitr and Sweave)

* vim

* jEdit

* Kate

* Revolution R Enterprise DevelopR (part of Revolution R Enterprise)

* Sublime Text

* TextMate

* Atom

* WinEdt (R Package RWinEdt)

* Tinn-R

* Notepad++

* IntelliJ IDEA

* Visual Studio

* Visual Studio Code

* Architect


시각화 패키지 

데이터를 그래프 등 보기 좋게 시각화해주는 패키지들 

* ggplot2

* ggvis

* googleVis

* rCharts

* ggiraphExtra

* plotly

* wordcloud


C#과 연동방법

* R.NET을 이용한 C# 연동

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Linq;
using RDotNet;
 
namespace Sample1
{
   class Program
   {
      static void Main(string[] args)
      {
         REngine.SetEnvironmentVariables();
         // There are several options to initialize the engine, but by default the following suffice:
         REngine engine = REngine.GetInstance();
 
         // .NET Framework array to R vector.
         NumericVector group1 = engine.CreateNumericVector(new double[] { 30.0229.9930.1129.9730.0129.99 });
         engine.SetSymbol("group1", group1);
         // Direct parsing from R script.
         NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();
 
         // Test difference of mean and get the P-value.
         GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
         double p = testResult["p.value"].AsNumeric().First();
 
         Console.WriteLine("Group1: [{0}]"string.Join(", ", group1));
         Console.WriteLine("Group2: [{0}]"string.Join(", ", group2));
         Console.WriteLine("P-value = {0:0.000}", p);
 
         // you should always dispose of the REngine properly.
         // After disposing of the engine, you cannot reinitialize nor reuse it
         engine.Dispose();
 
      }
   }
}
cs



* R 스크립트를 이용한 파일 실행

  아래와 같이 r 코드를 사용하여 name.r로 텍스트 파일을 만듭니다. rcodeTest.r로 이름을 지정했습니다.

library(RODBC) # you can write the results to a database by using this library
args = commandArgs(trailingOnly = TRUE) # allows R to get parameters
cat(as.numeric(args[1])+5)# converts 3 to a number (numeric)



아래에서와 같이 C# 클래스를 작성하세요. R 실행 파일을 실행 하기 위한 코드 입니다. 

 using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Linq;

using System.Web;

 

       /// <summary>

       /// Summary description for RScriptRunner

       /// </summary>

       public class RScriptRunner

       {

           public RScriptRunner()

           {

               //

               // TODO: Add constructor logic here

               //

           }

           // 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]);

           ///  

           ///   

           /// rCodeFilePath          - File where your R code is located.

           /// rScriptExecutablePath  - Usually only requires "rscript.exe"

           /// args                   - Multiple R args can be seperated by spaces.

           /// Returns                - a string with the R responses.

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

               }

           }

       }



그런 다음과 같은 매개 변수를 호출하고 전달하십시오.
result = RScriptRunner.RunFromCmd(path + @"\rcodeTest.r", @"D:\Programms\R-3.3.3\bin\rscript.exe", "3");

rscript.exe는 R 디렉토리에 있으며 path는 r 스크립트의 위치입니다 (rcodeTest.r)
다음과 같이 결과로 8 = 5 + 3의 결과를 얻을 수 있습니다.
Tag
R언어 , R, R 장단점,R 언어 C# 연동,r language
© Chaoreumsoft Corp. All rights reserved.