1

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

Will
  • 1,619
  • 5
  • 23

2 Answers2

3

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

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

setwd_n_levels(2)
getwd()
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use strrep

setwd_n_levels <- function(n) {
   setwd(trimws(strrep('../', n), whitespace = '/'))
  }
akrun
  • 874,273
  • 37
  • 540
  • 662