Question
Let's say my current file path obtained using basename is: a/b/c/d/e/f. How do I walk up to a particular directory, say c?
Nuances
I am trying to get a generalized solution to reach directory c. One way is to hard code and go few steps up by hard coding. I want to avoid it because I am working on a collaborative project and the local paths might differ when project files are handled by team members on different systems.
Existing questions
How to walk up a tree in R? : This question is more than 10 years old and is related with the webpages
https://stackoverflow.com/a/37381191/2761575: This is a hard-coded solution. Might not be suitable for collaborative projects.
Answer in an existing question
In R, how to find a file located in any parent directory upper than working directory? : This question focusses on finding the files, but the answers can be used to locate directory as well.
Answer pasted below for only convenience, credits to the original author.
find_up <- function(file, path=getwd()){
d <- dirname(path)
if(file.exists(here <- file.path(path, file))) here
else if(grepl('/', sub('/+$', '', d))) find_up(file, d)
else message('file does not exist')
}
Thank you community members for support.