04-29 02:46
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Big Data / Data Mining with R] Rscript 명령을 이용하여 Command Line에서 R 스크립트 파일 실행하기 본문

Data Science/Data Mining with R Programming

[Big Data / Data Mining with R] Rscript 명령을 이용하여 Command Line에서 R 스크립트 파일 실행하기

cinema4dr12 2016. 9. 21. 22:46

이번 글에서는 Rscript 명령을 통해 Command Line에서 R Script를 실행하는 방법을 알아 보도록 하겠다.

실행환경

  • OS : Windows 7 64

  • R : ver.3.3.1 Bug in Your Hair


환경변수 추가

만약 Default Option으로 R을 설치한 경우라면 Rscript.exe는 다음 경로에 있다.

C:\Program Files\R\R-3.3.1\bin


상기 기본 경로에 R을 설치하였다고 가정하고 환경변수 추가하는 방법에 대하여 알아본다.

Command Line에서 다음 명령을 입력하여 R 설치경로에 대한 변수를 추가한다:

> setx R_HOME "C:\Program Files\R\R-3.3.1\bin"


이제 Rscript.exe이 있는 경로(C:\Program Files\R\R-3.3.1\bin)를 PATH에 추가한다:

> PATH %PATH%;%R_HOME%


Command Line Tool을 종료한 후 재실행하여 Rscript.exe 명령이 실행되는지 확인한다:

> Rscript
Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]

--options accepted are
  --help              Print usage and exit
  --version           Print version and exit
  --verbose           Print information on progress
  --default-packages=list
                      Where 'list' is a comma-separated set
                        of package names, or 'NULL'
or options to R, in addition to --slave --no-restore, such as
  --save              Do save workspace at the end of the session
  --no-environ        Don't read the site and user environment files
  --no-site-file      Don't read the site-wide Rprofile
  --no-init-file      Don't read the user R profile
  --restore           Do restore previously saved objects at startup
  --vanilla           Combine --no-save, --no-restore, --no-site-file
                        --no-init-file and --no-environ

'file' may contain spaces but not shell metacharacters
Expressions (one or more '-e <expr>') may be used *instead* of 'file'
See also  ?Rscript  from within R


R Script 작성

\(\mathrm{log}_{a}{b}\)를 계산하는 R Script를 작성해 보자.

\(\mathrm{log}_{a}{b} = \displaystyle{\frac{\mathrm{log}_{10}{b}}{\mathrm{log}_{10}{a}}} , a > 0, a \ne 1, b > 0\)

이므로 다음과 같이 R Script를 작성할 수 있다:


[{YOUR_R_PROJ_PATH}/log_a_b.R]

log_a_b <- function(a, b) {
  if (b <= 0) {
    ret = "Error: b must be greater than 0";
    return(ret);
  }
  
  if (a <= 0) {
    ret = "Error: a must be greater than 0";
    return(ret);
  }
  else if (a == 1) {
    ret = "Error: a must not be 1";
    return(ret);
  }
  
  ret <- log10(b) / log10(a);
  return(ret);
}


예를 들어, \(\mathrm{log}_{2}{3}\)을 계산해 보자.

결과는 1.584963이다.

이제 Rscript.exe를 이용하여 Command Line에서 R 파일(함수)에 인수(Arguments)를 전달하려면 Wrapper Script 파일이 필요하다:


[{YOUR_R_PROJ_PATH}/log_wrapper.R]

args <- commandArgs(TRUE)
a <- as.double(args[1])
b <- as.double(args[2])

source("{YOUR_R_PROJ_PATH}/log_a_b.R")

val <- log_a_b(a, b)
cat(val)


Command Line에서 Rscript 실행

Command Line Tool에서 log_wrapper.R을 실행하려면 다음과 같이 입력한다:

> Rscript "{YOUR_R_PROJ_PATH}/log_wrapper.R" 2.0 3.0
1.584963

매우 간단하지 않은가!!!


Rscript 실행 결과값 저장

결과값을 임시 텍스트 파일(temp.txt)로 저장해 보도록 한다.

> Rscript "{YOUR_R_PROJ_PATH}/log_wrapper.R" 2.0 3.0 > temp.txt

현재 Command Line이 실행되는 경로에 "temp.txt"이 생성되어 있을 것이다.

이 파일을 열어보면 계산 결과가 저장되어 있는 것을 확인할 수 있을 것이다.

만약 "temp.txt"에 저장된 결과값을 Command Line에 변수를 정의하여 저장하고 싶다면 다음과 같이 명령을 입력한다:


> set /p VAR=<temp.txt
> echo %VAR%
1.584963


이로써 Command Line에서 Rscript 명령을 통해 R 파일을 실행하는 방법과 인수를 전달하는 방법 및 결과를 임시 텍스트에 저장하고 이로부터 변수에 저장하는 방법에 대하여 알아 보았다.

Comments