Search code examples
rdirectorypathcdsetwd

Go backward by N levels using setwd() in R


is there a way to go back in the directory using the R function setwd() by different levels?

for e.g.

> getwd() 
  /home/folder1/folder2/

I want to arrive in home in just one shot without typing setwd("../.."). It is very tedious to write n times "../"


Solution

  • One way would be to create the path "../.." dynamically.

    setwd_n_levels <- function(n) {
      setwd(paste0(rep('..', n), collapse = '/'))
    }
    
    setwd_n_levels(2)
    getwd()