When starting RStudio, I use the R/R-4.3.2/etc/Rprofile.site
to source custom functions written by myself. One of the customized functions uses this.path
to access the directory of whatever specific R file, which is calling the customized function with this.path
.
So I have a function RelPath()
sourced on start, calling it in Script.R, RelPath() does not return the path from Script.R but that of RelPath. This strange behaviour only appears when RelPath() is sourced from on start, not when I source it manually.
Probably a rooky mistake, but I cannot resolve it from related questions.
Rprofile.site contains one single line of code:
source("D:/.../OnStart.R")
OnStart.R
RelPath = function(MoveUpLevels = 1, Subdir){
Path = this.path::this.path()
# Move up x levels towards root directory to access directories of current R file
MoveUpLevels = MoveUpLevels + 1
if(MoveUpLevels > 0){
for(i in 1:MoveUpLevels){
Path = sub("/[^/]+$", "", Path)
}
}
# If sub directory is given, then check if it is exists
# If so, then add, else throw warning
if(!missing(Subdir)){
if(file.exists(file.path(Path,Subdir))){
Path=file.path(Path,Subdir)
}else{
warning(paste0("Given subdirectory is not found on system: ", file.path(Path,Subdir)))
}
}
return(Path)
}
Script.R
RelPath(0)
> "D:/.../OnStart.R"
I would have expected output: "E:/.../Script.R"
I'm the maintainer of package:this.path
.
this.path()
returns the path of the script in which it is written, which is not what you want. You could instead use sys.path()
which returns the path of the executing script. To demonstrate this distinction, try running example("sys.path")
.
This was a change I made in this.path 2.0.0 because of this issue: https://github.com/ArcadeAntics/this.path/issues/13
You could also refer to news(package = "this.path")
specifically section Changes in version 2.0.0
subsection Significant User-Visible Changes
where I explain why I made those changes.
Sorry for the confusion. If you have any suggestions for how I can improve the documentation to make it easier for other users to understand, that'd be great, thank you!
One more thing, @Konrad Rudolph mentioned using argument n
to this.path()
. That is another option, though I will have a hard time explaining it concisely here. You can refer to section Argument 'n'
of ?this.path
if you'd like to see how to use it.