2017-01-10 8 views
0

R 프로그램의 파일 이름/파일 경로를 파생시킬 수 있는지 알고있는 사람이 있습니까? 나는 "% sysfunc (GetOption (SYSIN))"SAS 프로그램 (배치 모드에서 실행 중)의 파일 경로를 반환하는 SAS와 비슷한 것을 찾고 있습니다. R에서 비슷한 것을 할 수 있습니까?R 프로그램의 파일 이름 또는 파일 경로 사용

내가 지금까지 생각해 낼 수 있었던 최선의 방법은 내가 사용하는 텍스트 편집기 (PSPad)에서 바로 가기 키를 사용하여 파일 이름과 현재 디렉토리를 추가하는 것입니다. 이 작업을 수행하는 더 쉬운 방법이 있습니까? 이것은 일괄 및 RStudio 모두 상당히 잘 작동

progname<-"Iris data listing" 

# You must use either double-backslashes or forward slashes in pathnames 
progdir<-"F:\\R Programming\\Word output\\" 
# Set the working directory to the program location 
setwd(progdir) 

# Make the ReporteRs package available for creating Word output 
library(ReporteRs) 
# Load the "Iris" provided with R 
data("iris") 

options('ReporteRs-fontsize'=8, 'ReporteRs-default-font'='Arial') 

# Initialize the Word output object 
doc <- docx() 
# Add a title 
doc <- addTitle(doc,"A sample listing",level=1) 

# Create a nicely formatted listing, style similar to Journal 
listing<-vanilla.table(iris) 

# Add the listing to the Word output 
doc <- addFlexTable(doc, listing) 

# Create the Word output file 
writeDoc(doc, file = paste0(progdir,progname,".docx")) 

:

은 여기 내 예입니다. 나는 더 나은 해결책을 정말로 고맙겠습니다.

+0

는 찾고있는이 관련이있다.? [RSCRIPT : 실행중인 스크립트의 경로를 결정] : // 유래 (HTTP를. co.kr/questions/1815606/rscript-determine- 실행중인 스크립트의 경로) –

+0

감사합니다. 링크를 클릭하십시오. 거기에 많은 정보가 있지만 지금까지는 RStudio 나 배치 명령 파일에서 직접 작동하는 솔루션이 없습니다. R 프로그램이 RStudio에서 제공되는 경우 솔루션 중 일부가 작동한다고 생각하지만 실제로 찾고있는 것은 아닙니다. "rterm < source.r > output.r"대신 "rterm --file ="을 사용하도록 배치 파일을 조정할 수 있었지만 아직 시도하지 않았습니다. – ckx

답변

1

@Juan Bosco가 제공 한 Rscript: Determine path of the executing script에 대한 링크에는 필요한 정보가 대부분 포함되어 있습니다. RStudio에서 R 프로그램을 실행하는 문제가있었습니다 (RStudio에서 소싱이 논의되고 해결되었습니다). 이 문제는 rstudioapi::getActiveDocumentContext()$path)을 사용하여 처리 할 수 ​​있음을 발견했습니다.

그것은 배치 모드에 대한 솔루션을

Rterm.exe --no-restore --no-save < %1 > %1.out 2>&1 

용액 필요한 --file= 옵션을 사용하는 것이, 예를 들어,를 사용하여 작동하지 않습니다 또한 주목할입니다

D:\R\R-3.3.2\bin\x64\Rterm.exe --no-restore --no-save --file="%~1.R" > "%~1.out" 2>&1 R_LIBS=D:/R/library 

여기 @aprstar에 의해 게시 get_script_path 기능의 새로운 버전입니다. 이 또한 RStudio에서 작동하도록 수정되었습니다 (가 rstudioapi 라이브러리가 있어야한다는 사실을 명심해야합니다.

# Based on "get_script_path" function by aprstar, Aug 14 '15 at 18:46 
# https://stackoverflow.com/questions/1815606/rscript-determine-path-of-the-executing-script 
# That solution didn't work for programs executed directly in RStudio 
# Requires the rstudioapi package 
# Assumes programs executed in batch have used the "--file=" option 
GetProgramPath <- function() { 
    cmdArgs = commandArgs(trailingOnly = FALSE) 
    needle = "--file=" 
    match = grep(needle, cmdArgs) 
    if (cmdArgs[1] == "RStudio") { 
     # An interactive session in RStudio 
     # Requires rstudioapi::getActiveDocumentContext 
     return(normalizePath(rstudioapi::getActiveDocumentContext()$path)) 
    } 
    else if (length(match) > 0) { 
     # Batch mode using Rscript or rterm.exe with the "--file=" option 
     return(normalizePath(sub(needle, "", cmdArgs[match]))) 
    } 
    else { 
     ls_vars = ls(sys.frames()[[1]]) 
     if ("fileName" %in% ls_vars) { 
      # Source'd via RStudio 
      return(normalizePath(sys.frames()[[1]]$fileName)) 
     } 
     else { 
      # Source'd via R console 
      return(normalizePath(sys.frames()[[1]]$ofile)) 
     } 
    } 
} 

내가 지금은 사용하여 다음 중 하나를 배치 모드 나 RStudio의 파일 정보를 얻을 수 있습니다. 내 .Rprofile 파일이 배치 . 코드가 나는 source()를 사용하지만 너무 작동합니다 시도하지 않은

# "GetProgramPath()" returns the full path name of the file being executed 
progpath<-GetProgramPath() 
# Get the filename without the ".R" extension 
progname<-tools::file_path_sans_ext(basename(progpath)) 
# Get the file directory 
progdir<-dirname(progpath) 
# Set the working directory to the program location 
setwd(progdir)