Nice programing

R : 상대 경로를 사용하여 파일 소싱

nicepro 2020. 12. 25. 22:56
반응형

R : 상대 경로를 사용하여 파일 소싱


상대 경로를 사용하는 파일 소싱은 대규모 코드베이스를 처리 할 때 유용합니다. 다른 프로그래밍 언어에는 소싱되는 파일의 디렉토리에 상대적인 경로를 사용하여 파일 소싱을위한 잘 정의 된 메커니즘이 있습니다. 예는 Ruby의 require_relative. R에서 상대 경로 소싱을 구현하는 좋은 방법은 무엇입니까?

아래는 다양한 요리법과 R 포럼 게시물을 사용하여 잠시 모아 놓은 것입니다. 직접적인 개발에는 잘 작동했지만 견고하지는 않습니다. 예를 들어 파일이 testthat라이브러리 를 통해로드 될 때 중단됩니다 auto_test(). 특히 . rscript_stack()를 반환합니다 character(0).

# Returns the stack of RScript files
rscript_stack <- function() {
  Filter(Negate(is.null), lapply(sys.frames(), function(x) x$ofile))
}

# Returns the current RScript file path
rscript_current <- function() {
  stack <- rscript_stack()
  r <- as.character(stack[length(stack)])
  first_char <- substring(r, 1, 1)
  if (first_char != '~' && first_char != .Platform$file.sep) {
    r <- file.path(getwd(), r)
  }
  r
}

# Sources relative to the current script
source_relative <- function(relative_path, ...) {
  source(file.path(dirname(rscript_current()), relative_path), ...)
}

더 나은 source_relative구현 을 알고 있습니까?


GitHub에서 @hadley와 토론 한 후 내 질문이 R의 일반적인 개발 패턴에 위배된다는 것을 깨달았습니다.

종종 공급됩니다 R에서 파일을 작업 디렉토리가 (가정 것 같다 getwd(),이 일을 위해.)가에있는 디렉토리로 설정됩니다 sourcechdir그 기본 값이 인수를 FALSE. 로 설정 TRUE하면 작업 디렉토리가 소스 파일의 디렉토리로 변경됩니다.

요약하자면:

  1. source소싱되는 파일의 작업 디렉토리가 파일이있는 디렉토리로 설정되기 때문에 항상 상대적 이라고 가정합니다 .

  2. 이 작업을 수행하려면 항상 chdir=T다른 디렉토리 (예 : source('lib/stats/big_stats.R', chdir=T).

예측 가능한 방식으로 전체 디렉토리를 편리하게 소싱 sourceDir하기 위해 사전 순으로 디렉토리의 파일을 소싱하는 .

sourceDir <- function (path, pattern = "\\.[rR]$", env = NULL, chdir = TRUE) 
{
    files <- sort(dir(path, pattern, full.names = TRUE))
    lapply(files, source, chdir = chdir)
}

참조 URL : https://stackoverflow.com/questions/12048436/r-sourcing-files-using-a-relative-path

반응형