Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent directory in R

Tags:

r

People also ask

What is a parent directory?

In computing terms, a parent directory is a directory that is above another directory. The root directory is the only directory that cannot be put below any other directory. The directory below the parent directory is the subdirectory. The directory path looks like this: root directory/parent directory/subdirectory.

Where is the parent directory?

Every directory, except the root directory, lies beneath another directory. The higher directory is called the parent directory, and the lower directory is called a subdirectory.

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

How do I get the directory path in R?

If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ).


You can use dirname on getwd to extract everything but the top most level of your current directory:

dirname(getwd())
[1] "C:/Documents and Settings"

Actually dirname allows to go back to several parent folders

Path="FolderA/FolderB/FolderC/FolderD"

dirname(Path)

"FolderA/FolderB/FolderC"

dirname(dirname(Path))

"FolderA/FolderB"

And so on...


I assume you mean parent directory of R's working directory?

The simplest solution is probably as follows.

wd <- getwd()
setwd("..")
parent <- getwd()
setwd(wd)

This saves the working directory, changes it to its parent, gets the result in parent, and resets the working directory again. This saves having to deal with the vagaries of root directories, home directories, and other OS-specific features, which would probably require a bunch of fiddling with regexes.


Possibly these two tips may help

"~/"  # after the forward slash you "are" in your home folder

then on windows

"C:/" # you are in your main hard drive
"G:/" # you are just in another hard drive :-)

on unix you can do something similar with

"/etc/"

then you can go down into any sub directory you need

Or as @Hong Ooi suggests you can go up to the parent dir of your working directory with

"../"

NB: just after the final forward slash press tab and you'll have all the file and folder, very handy, especially in RStudio


Another possibility:

parts <- unlist(strsplit(getwd(), .Platform$file.sep))
do.call(file.path, as.list(parts[1:length(parts) - 1]))

This splits the filepath into directories, drops the last directory, and then recombines the parts into a filepath again.