Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain a list of directories within a directory, like list.files(), but instead "list.dirs()"

Tags:

directory

r

This may be a very easy question for someone - I am able to use list.files() to obtain a list of files in a given directory, but if I want to get a list of directories, how would I do this? Is it somehow right in front of me as an option within list.files()?

Also, I'm using Windows, so if the answer is to shell out to some Linux/unix command, that won't work for me.

.NET for example has a Directory.GetFiles() method, and a separate Directory.GetDirectories() method, so I figured R would have an analogous pair. Thanks in advance.

like image 420
user297400 Avatar asked Jan 20 '11 16:01

user297400


People also ask

How do I get a list of directories in a directory?

Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.


2 Answers

Update: A list.dirs function was added to the base package in revision 54353, which was included in the R-2.13.0 release in April, 2011.

list.dirs(path = ".", full.names = TRUE, recursive = TRUE) 

So my function below was only useful for a few months. :)


I couldn't find a base R function to do this, but it would be pretty easy to write your own using:

dir()[file.info(dir())$isdir] 

Update: here's a function (now corrected for Timothy Jones' comment):

list.dirs <- function(path=".", pattern=NULL, all.dirs=FALSE,   full.names=FALSE, ignore.case=FALSE) {   # use full.names=TRUE to pass to file.info   all <- list.files(path, pattern, all.dirs,            full.names=TRUE, recursive=FALSE, ignore.case)   dirs <- all[file.info(all)$isdir]   # determine whether to return full names or just dir names   if(isTRUE(full.names))     return(dirs)   else     return(basename(dirs)) } 
like image 94
Joshua Ulrich Avatar answered Oct 03 '22 12:10

Joshua Ulrich


base R now includes a list.dirs function, so home-brewed variants are no longer necessary.

For example:

list.dirs('.', recursive=FALSE) 
like image 45
jbaums Avatar answered Oct 03 '22 13:10

jbaums