Home > database >  Coding a relative path to a shared directory in R
Coding a relative path to a shared directory in R

Time:04-11

Let's say my colleagues and I have a shared directory, such as a SharePoint drive. Our file path to any given directory, say OurProject1 will be the same with the only difference being our username.

So for example my path will be: "C:/Users/JohnLennon/SharedDrive/SharedData/baseline_data"

While theirs will be: "C:/Users/RingoStarr/SharedDrive/SharedData/baseline_data"

I am trying to write a function that will allow any of my colleagues who has mapped the shared drive to run a script that accesses data in the shared data without them having to manually input their username. Keep in mind that the project directory is not the shared drive - that if I share this script with a colleague it will be kept outside of the shared directory and so relative file paths with regards to the project won't work.

I have been trying to approach this using an absolute file path set temporarily within the function that infers the first half of the directory path from getwd(). So the function looks a bit like this:

wd <- getwd() # get the users working dir
usr <- substr(wd, 1, 18) # extract the root down to the username
paste(usr, "SharedDrive/SharedData/baseline_data", sep = "") # prefix this onto the shared directory path

This works fine for RingoStarr, who has the same number of characters in his username as JohnLennon, but what about GeorgeHarrison, or all the other users? Counting characters on line two is clearly a limited approach.

I am looking for a modification to line two that will navigate "blindly" from the working directory, which we assume to be a subdirectory of "C:/Users/Username/" to two levels below the root directory (i.e. in the Username directory). ".." won't work here as we don't know where abouts within the the Username directory getwd() is.

I am also open to a different approach to the problem if one exists

CodePudding user response:

Instead of substr, you can try strsplit and then paste:

wd_split <- strsplit(wd, "\\/")
wd_split
# [[1]]
# [1] "C:"          "Users"       "JohnLennon"  "SharedDrive" "SharedData" 

usr <- paste(wd_split[[1]][1:3], collapse = "/")
usr
# "C:/Users/JohnLennon"
  • Related