R does not store nor export the path of the currently running script. This is an attempt to circumvent this limitation by applying heuristics (such as call stack and argument inspection) that work in many cases. CAVEAT: Use this function only if your workflow does not permit other solution: if a script needs to know its location, it should be set outside the context of the script if possible.

thisfile()

thisfile_source()

thisfile_r()

thisfile_rscript()

thisfile_knit()

Value

The path of the currently running script, NULL if it cannot be determined.

Details

This functions currently work only if the script was sourced, processed with knitr, or run with Rscript or using the --file parameter to the R executable. For code run with Rscript, the exact value of the parameter passed to Rscript is returned.

Note

These functions were migrated from r-lib/rprojroot.

Author

Kirill Müller, Hadley Wickham, Michael R. Head

Examples


if( !interactive() )
  thisfile()
#> [1] "/home/runner/work/_temp/7a6570a7-4eb5-4e2a-a9f8-61be4498307e"

# using in terminal ( with pipe() )

  # open a temp file
   tf <- tempfile(fileext = '.R')

  # call to write to temp file
   f <- 'cat(whereami::thisfile(), "\n", sep = "")'

  # write to the file
   cat(f,file = tf)

  # create an R call to terminal
   fcmd <- sprintf('"%s" --slave --vanilla --no-save -f %s',R.home('bin/R'),tf)

  # run the call
   p <- pipe(fcmd)

  # read the output
   readLines(p)
#> [1] "/tmp/Rtmp8T36Ny/file2d3c5a13502b.R"

  # cleanup
   close(p)
   unlink(tf)