ckx
ckx

Reputation: 98

Use the filename or filepath in R programs

Does anyone know if it's possible to derive the filename/filepath of an R program? I'm looking for something similar to "%sysfunc(GetOption(SYSIN))" in SAS which will return the filepath of a SAS program (running in batch mode). Can I do anything similar in R?

The best I've been able to come up with so far is to add the filename and current directory using shortcut keys in the text editor I use (PSPad). Is there an easier way to do this?

Here's my example:

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"))

This works fairly well, both in batch and in RStudio. I'd really appreciate a better solution though

Upvotes: 0

Views: 868

Answers (1)

ckx
ckx

Reputation: 98

The link to Rscript: Determine path of the executing script provided by @Juan Bosco contained most of the information I needed. One problem it didn't address was running an R program in RStudio (sourcing in RStudio was discussed and solved). I found that this problem could be dealt with using rstudioapi::getActiveDocumentContext()$path).

It's also noteworthy that the solutions for batch mode won't work using

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

The solutions require that the --file= option be used, e.g.

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

Here's a new version of the get_script_path function posted by @aprstar. This has been modified to also work in RStudio (note that it requires the rstudioapi library.

# 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))
        }
    }
}

I placed this in my .Rprofile file. Now I can get the file information in either batch mode or in RStudio using the following code. I haven't tried it using source() but that should work too.

# "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)

Upvotes: 1

Related Questions