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.
What about something like this, give it a try:
might be of use?
How might we do this recursively? (the
recursive
argument ofdir
breaks these functions because it never returns directory names, just the files within each directory, etc...).base
R now includes alist.dirs
function, so home-brewed variants are no longer necessary.For example:
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.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:
Update: here's a function (now corrected for Timothy Jones' comment):
I had this problem a while back and used this recursive code to find all directories. Perhaps this can be of use?
You mention that you don't want to shell out to a Linux/UNIX command but I assume its ok to shell out to a Windows command. In that case this would do it:
and this would do it recursively:
Normally I would prefer the platform independent solutions of others here but particularly for interactive use where you are just concerned with getting the answer as simply and directly as possible this may be less work.