Go backward by N levels using setwd() in R

77 Views Asked by At

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 "../"

2

There are 2 best solutions below

0
Ronak Shah On BEST ANSWER

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

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

setwd_n_levels(2)
getwd()
0
akrun On

We can use strrep

setwd_n_levels <- function(n) {
   setwd(trimws(strrep('../', n), whitespace = '/'))
  }