-1

I want to find the directory where my R code file is located. If I attempt to

source("dir/hh.R") 

then I would need to know in advance the directory in which the script is located. I would like to automatically identify the directory of my script, so I can call it like this:

pathToMyScript <- findDirectoryOfMyScript("hh.R")
source(paste0(pathToMyScript, "/hh.r"))

What function can I used to find automatically the path of my R code? What would be findDirectoryOfMyScript like?

PavoDive
  • 6,322
  • 2
  • 29
  • 55
kamal
  • 89
  • 1
  • 7
  • Not clear what you're asking. Possibly a duplicate of [Get the path of current script](https://stackoverflow.com/questions/47044068/get-the-path-of-current-script/47045368) ? – neilfws Aug 06 '19 at 01:50
  • this link has dependency of Rstudio. It is working in Rstudio. was looking one that would work in R console. – kamal Aug 06 '19 at 02:56
  • There are solutions other than for RStudio at that link, if you scroll down. – neilfws Aug 06 '19 at 03:08
  • saw that. none other than green tick seems to work. – kamal Aug 06 '19 at 03:36

1 Answers1

0

If you happen to know the name of the script but not the directory it's stored in, you can source it like this:

source(list.files(pattern = "nameOfFile.R", recursive = TRUE))

Notice that you can actually set a real pattern instead of the actual filename, like I used in the example.

Please be aware that if there are more than one file returned by the search done by list.files, source will return an error.

PavoDive
  • 6,322
  • 2
  • 29
  • 55