YOGYUI

R 스크립트 파일 경로 가져오기 본문

Software/R

R 스크립트 파일 경로 가져오기

요겨 2021. 6. 5. 11:27
반응형

파이썬은 __file__ 변수를 통해 현재 실행되는 스크립트의 절대경로를 쉽게 가져올 수 있다

R은 이리저리 검색해보니 tidyverse 라이브러리를 사용한 함수를 활용하는게 제일 확실한 것 같다

출처: https://stackoverflow.com/questions/47044068/get-the-path-of-current-script

 

# install.packages("tidyverse")
library(tidyverse)

getCurrentFileLocation <-  function()
{
  this_file <- commandArgs() %>% 
    tibble::enframe(name = NULL) %>%
    tidyr::separate(col=value, into=c("key", "value"), sep="=", fill='right') %>%
    dplyr::filter(key == "--file") %>%
    dplyr::pull(value)
  if (length(this_file)==0)
  {
    this_file <- rstudioapi::getSourceEditorContext()$path
  }
  return(dirname(this_file))
}

shell에서 실행할 경우 명령줄 인자(argument)를 파싱해서 실행 스크립트 파일이 포함된 디렉터리의 경로를 반환하며, R Studio로 실행할 경우 rstudioapi의 getSourceEditorContext() 함수를 사용한다

 

위 함수를 사용해서 실행되는 스크립트 파일의 디렉터리를 작업경로로 설정할 수 있다

# install.packages("tidyverse")
library(tidyverse)

getCurrentFileLocation <-  function()
{
  this_file <- commandArgs() %>% 
    tibble::enframe(name = NULL) %>%
    tidyr::separate(col=value, into=c("key", "value"), sep="=", fill='right') %>%
    dplyr::filter(key == "--file") %>%
    dplyr::pull(value)
  if (length(this_file)==0)
  {
    this_file <- rstudioapi::getSourceEditorContext()$path
  }
  return(dirname(this_file))
}

setwd(getCurrentFileLocation())

 

 

반응형
Comments