45

In R, I'm working on "./parent/Child/A". I want to move back parent folder "child", but when I type full path. It lost many times.

Jame H
  • 1,324
  • 4
  • 15
  • 26
  • 1
    How exactly did you "type full path" and what do you mean "it lost many times?" Can you show some code? – MrFlick Jun 20 '14 at 02:45
  • Ok. I usually code like this: setwd("./parent/Child"). With short path as this example, it ok. But with long path, it's not good for me. – Jame H Jun 20 '14 at 02:56

5 Answers5

78
setwd('..')

will move up one directory without entering the absolute path. Here's an example

> getwd()
[1] "C:/Users/D/Desktop/EDABaseball"
> setwd('..')
> getwd()
[1] "C:/Users/D/Desktop"
16

I think you want to move back to the working directory ./parent/Child/. This can be done in 2 ways, assuming your current working directory is ./parent/Child/A

1) setwd("..")

2) setwd("./..")

3) setwd("./parent/Child")

Brouwer
  • 651
  • 1
  • 4
  • 17
  • 5
    what is the difference between using one or two dots? I had to go back two folders up and had to use "../../analisys/data" – niklai Mar 30 '17 at 14:20
  • 4
    @niklai to go back two levels in your directory hierarchy you'd enter the command `setwd("./../..")` and to move back three levels you'd enter the command `setwd("./../../..")` and so on. – Display name Nov 04 '19 at 16:33
  • Double quotes does not work in my Linux Mint. Single ones, do. – Sigur Jan 30 '20 at 15:33
12

I also find dirname() function pretty useful especially if your path is saved in a variable:

mypath <- getwd()

# The path of the parent directory:
dirname(mypath)
HBat
  • 4,873
  • 4
  • 39
  • 56
  • dirname is appropriate if one would like to just move one directly out of working directory. very useful. Thank you @HBat – sveer Jan 12 '21 at 10:00
4

Moves up one directory in Linux

setwd("../")
Koundy
  • 5,265
  • 3
  • 24
  • 37
0

Basically I split the child folder using strsplit by '/' and then got the parent folder pasting the slices collapsing by '/', except for the last one. I used getwd() to make the code reproducible, but you may use any folder.

myDir <- unlist(strsplit(getwd(), '/'))
paste0(myDir[-length(myDir)], collapse = '/')
zabala
  • 103
  • 1
  • 7