如何使用 Recall() 编写递归函数来递归列出给定目录中的目录?
这个问题 询问当前目录中的目录(不是文件)的列表。我在对其中一个答案的评论中指出,我们不能使用 dir
和 list.files
等函数的 recursive
参数来递归列出当前目录中的目录。
对此的明显解决方案是编写一个递归函数,列出当前目录中的目录,该函数依次在每个目录上调用自身,依此类推,添加到在递归结束时返回的目录的总体列表中。
Recall()
函数似乎是这种情况的理想候选者,但我从来没有真正理解如何编写一个递归函数,该函数在每次调用时都会添加到最终输出中。
如何修改此函数:
list.dirs <- function(path) {
x <- dir(path, full.names = TRUE)
dnames <- x[file_test("-d", x)]
dnames
}
让它递归地遍历 dnames
中的目录,将它找到的任何目录添加到 dnames
目录中找到的所有目录的列表中,等等在...?
This Question asked about listing directories (not files) in the current directory. I noted in a comment to one of the answers that we can't use the recursive
argument of functions like dir
and list.files
to recursively list directories in the current directory.
The obvious solution to this is to write a recursive function that lists the directories in the current directory that calls itself on each of those directories in turn, and so on, adding to the overall list of directories that gets returned at the end of the recursion.
The Recall()
function would seem the ideal candidate for this, but I've never really got my head round how one writes a recursive function that adds to the final output each time it is called.
How would one modify this function:
list.dirs <- function(path) {
x <- dir(path, full.names = TRUE)
dnames <- x[file_test("-d", x)]
dnames
}
To have it descend recursively through the directories in dnames
adding any directories it finds to a list of all directories found within the dnames
directories, and so on...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种方法:
这只是将子目录添加到末尾,可以使用一些不同的逻辑来给出不同的顺序。
Here is one way:
This just tacks the subdirectories onto the end, some different logic could be used to give a different ordering.