2019년 2월 13일

자바 웹 프로그램에서 R 언어 사용하기

자바에서 R 을 사용하는 방법에는 Rserve 라 불리우는 바이너리 R 서버를 이용하여 원격으로 R 언어를 사용하는 방법이 있다.


설치 환경
  • OS : CentOS Linux release 7.6.1810 (Core)

R 설치하기

R설치는 여러 방법이 있으나 yum (패키지 관리자) 도구를 사용하면 쉽게 설치가 가능하다.

yum install R

설치된 R 모듈 확인은 아래와 같은 명령으로 확인 할 수 있다.

yum list R-\*

설치가 완료되면 R 명령을 입력하여 R 명령을 실행하는 R 콘솔을 실행 할 수 있다.

#R

R version 3.5.1 (2018-07-02) -- "Feather Spray"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-redhat-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> 

RServe 설치하기

RServe 설치는 공식 가이드 문서 에서 권고하는 방식으로 R 콘솔에서 install.packages 명령을 사용하였다.

install.packages('Rserve' , , 'http://www.rforge.net/')

만일 설치중에 아래와 같이  lssl 을 찾을 수 없다는 오류가 발생하는 경우 yum 을 사용 openssl-devel 모듈을 설치하고 다시 시도한다.



yum install openssl-devel

설치가 완료되면  Rserve 는 아래와 같이 R 콘솔에서 명령을 입력하여 실행할 수 있다.

library(Rserve)
Rserve()
Starting Rserve:
/usr/lib64/R/bin/R CMD /usr/lib64/R/library/Rserve/libs//Rserve 
R version 3.5.1 (2018-07-02) -- "Feather Spray"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-redhat-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

Rserv started in daemon mode.


클라이언트에서 원격 호출을 위하여 아래와 같이 설정을 추가하고 Rserve 데몬을 다시 시작한다.

① /etc/Rserv.conf 파일을 생성하고 아래와 같이 기술한다. 
주의할 것은 pwdfile 는 원격접속시 사용되는 사용자의 아이디와 비밀번호를 평문으로 기술하고 있는 파일을 의미하며 한글 사용을 위해서는 encoding  값을 utf8 로 설정해야 한다.

/etc/Rserv.conf
remote enable
port 6311
plaintext enable
auth required
pwdfile /etc/Ruser.txt
encoding utf8


/etc/Ruser.txt ( rserv/rserv  계정을 추가)
rserv rserv


② Rserv 데모 프로세스를 아래와같이 프로세스 아이디를 검색하여 kill 명령으로 종료한다.

#ps -ef | grep Rserve
root     53124     1  0 15:36 ?        00:00:00 /usr/lib64/R/library/Rserve/libs//Rserve --RS-conf /etc/Rserv.conf --no-save --RS-port 6311
root     53174 52602  0 15:37 pts/1    00:00:00 grep --color=auto Rserve
# kill -9 53124

③ R 콘솔에서 아래와 같은 명령으로 Rserve 데몬을 실행한다.

library(Rserve)
Rserve(port=6311, args="--RS-conf /etc/Rserv.conf --no-save")

④ 방화벽을 사용하고 있다면 다음의 명령으로 외부에서 6311 포트로 접속이 가능하게 접속을 허용한다.

firewall-cmd --permanent --zone=public --add-port= 6311/tcp

firewall-cmd --reload


자바에서 R 사용하기

자바에서 Rserve 를 사용하려면

  • 자바 1.4 이상 
  • Rserve 클라이언트 라이브러리 (REngine.jar, RserveEngine.jar ) 

가 필요하다. 라이브러리는 아래 경로에서 다운로드 할 수 있다.

https://rforge.net/Rserve/files/

다음은 간단하게 리모트롤 R를 사용하는 예제이다.

import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
 
 public class Rserve {
 
     public static void main(String a[]) {
         RConnection connection = null;
 
         try {
             /* Create a connection to Rserve instance running
              * IP Addr, UserID, Password required (/etc/Ruser.txt)
              */
             connection = new RConnection("IP주소", 6311);
             connection.login("계정","비번");
             String vector = "c(1,2,3,4)";
             connection.eval("meanVal=mean(" + vector + ")");
             double mean = connection.eval("meanVal").asDouble();
             System.out.println("The mean of given vector is=" + mean);
             
            REXP x = connection.eval("R.version.string");
 	    System.out.println(x.asString()); 
 	    double[] myvalues = {1.0, 1.5, 2.2, 0.5, 0.9, 1.12}; 
 	    connection.assign("myvalues", myvalues); 
	    x = connection.eval("mean(myvalues)"); 
	    System.out.println(x.asDouble()); 
	    x = connection.eval("sd(myvalues)"); 
	    System.out.println(x.asDouble());

         } catch (Exception e) {
             e.printStackTrace();
         }finally{
             connection.close();
         }
     }
 } 



아직까지는 R 언의 문법이나 사용법을 충분하게 인지하지 못하고 있기 때문에 사용을 위해서는 더많은 R 관련 학습이 필요할 것 같다.


참고자료

  1. https://cran.r-project.org/bin/linux/redhat/README
  2. https://stackoverflow.com/questions/25979525/cannot-find-lssl-cannot-find-lcrypto-when-installing-mysql-python-using-mar
  3. https://www.rforge.net/Rserve/doc.html
  4. https://datamashupblog.wordpress.com/2017/11/04/setting-up-r-in-aws/

댓글 2개: