如何获取目录中的目录列表,如list.files(),而是“list.dirs()” [英] How to obtain a list of directories within a directory, like list.files(), but instead "list.dirs()"

查看:1015
本文介绍了如何获取目录中的目录列表,如list.files(),而是“list.dirs()”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常容易的问题 - 我可以使用 list.files()来获取给定目录中的文件列表,但如果我想得到目录列表,我该怎么做?在$ code> list.files()?

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()?

另外,我' m使用Windows,所以如果答案是shell出来一些Linux / unix命令,这将不适用于我。

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例如有一个 Directory.GetFiles()方法和一个单独的 Directory.GetDirectories()
方法,所以我认为R会有一个类似的对。感谢提前。

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

推荐答案

更新:A list.dirs 函数是添加到版本54353的基础包中,该包已包含在2011年4月的R-2.13.0版本中。

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. :)

我找不到一个基本的R函数来做到这一点,但写起来很简单自己使用:

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]

更新:这是一个函数(现在更正了Timothy Jones的评论):

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))
}

这篇关于如何获取目录中的目录列表,如list.files(),而是“list.dirs()”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆