R:深度嵌套列表中的递归函数:层次结构的访问级别 [英] R: Recursive function in deeply nested list: Accessing level of hierarchy

查看:56
本文介绍了R:深度嵌套列表中的递归函数:层次结构的访问级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于兴趣和思考的目的,我的目的是复制 功能从R中的Windows命令行开始. tree 生成类似ASCII树到以下示例(取自此处并修改).如果 n 是层次结构级别,请注意每个文件或文件夹具有(n-1)* 3 个空格,后跟 + ---

Out of interest and as a thought exercise, I was aiming to replicate the tree function from the windows command line in R. tree generates ASCII trees similar to the following example (taken from here and modified). If n is the hierarchical level, note that each file or folder has (n-1)*3 spaces, followed by +---

+---Desktop
+---Documents
    +---Custom Office Templates
    +---Fiddler2
        +---Captures
            +---Requests
            +---Responses
        +---Scripts
+---Favorites
    +---Links

我使用 list.files()提取文件名(尽管此功能忽略空目录)和递归函数 dir_tree()(灵感来自此答案)来捕获嵌套列表中的层次结构.

I use list.files() to extract the filenames (albeit this function ignores empty directories) and the recursive function dir_tree() (inspired by this answer) to capture the hierarchy in a nested list.

library(purrr)
library(stringr)
dirs <- list.files(recursive = TRUE) 

# To create a reproducible example, I create dirs manually
dirs <- c("Desktop",
          "Documents",
          "Documents/Custom Office Templates",
          "Documents/Fiddler2",
          "Documents/Fiddler2/Captures",
          "Documents/Fiddler2/Captures/Requests",
          "Documents/Fiddler2/Captures/Responses",
          "Documents/Fiddler2/Scripts",
          "Documents/Favorites",
          "Documents/Favorites/Links"
)

dir_tree <- function(dirs) {
  first <- map_chr(str_split(dirs,"/"),~.x[1])
  rest  <- map_chr(str_split(dirs,"/"),~paste(.x[-1],collapse = "/"))
  zi    <- nchar(dirs) == 0L 
  myli <- split(rest[!zi], first[!zi])
  map(myli, ~dir_tree(.x))
}

# creates a nested list
dir_nl <- dir_tree(dirs)

str(dir_nl)

## List of 2
##  $ Desktop  : Named list()
##  $ Documents:List of 3
##   ..$ Custom Office Templates: Named list()
##   ..$ Favorites              :List of 1
##   .. ..$ Links: Named list()
##   ..$ Fiddler2               :List of 2
##   .. ..$ Captures:List of 2
##   .. .. ..$ Requests : Named list()
##   .. .. ..$ Responses: Named list()
##   .. ..$ Scripts : Named list()

我现在要做的就是递归地浏览嵌套列表,然后打印名称,并在名称前加上(n-1)* 3 空格和 + --- .这我的问题是:如何检索 n ,即层次结构级别!?

All I need to do now is to walk recursively through the nested list and print the names, prepending it with (n-1)*3 spaces and +---. The Question I have is: How do I retrieve n, i.e. the hierarchical level!?

recursive_print <- function(dir_nl){
  imap(dir_nl,function(x,y){
    if(is.list(x)){
      print(paste("+---",y))
      recursive_print(x)
    } 
  })
}


recursive_print(dir_nl) %>% invisible()

## [1] "+--- Desktop"
## [1] "+--- Documents"
## [1] "+--- Custom Office Templates"
## [1] "+--- Favorites"
## [1] "+--- Links"
## [1] "+--- Fiddler2"
## [1] "+--- Captures"
## [1] "+--- Requests"
## [1] "+--- Responses"
## [1] "+--- Scripts"

推荐答案

我自己无法解决问题,但是找到了一个可以帮我解决问题的软件包.这种做法违背了学习递归函数的目的,但是我会把它放在这里,以防有人落入这里.

I haven't been able to solve it myself, but found a package that does it for me. This kind of defeats the purpose of learning recursive functions, but I'll place this here in case anyone lands here.

library(data.tree)

tree <- FromListSimple(dir_nl)

print(tree)

##                          levelName
## 1  Root                           
## 2   ¦--Desktop                    
## 3   °--Documents                  
## 4       ¦--Custom Office Templates
## 5       ¦--Favorites              
## 6       ¦   °--Links              
## 7       °--Fiddler2               
## 8           ¦--Captures           
## 9           ¦   ¦--Requests       
## 10          ¦   °--Responses      
## 11          °--Scripts

为了便于记录, data.tree 具有一种将文件路径字符串直接解析到树中的方法,因此 dir_tree()变得过时了.

And for the record, data.tree has a method to directly parse a string of filepaths into a tree, so dir_tree() becomes obsolete.

as.Node(data.frame(paths = dirs),pathName = "paths")

##                     levelName
## 1 Desktop                    
## 2  ¦--Custom Office Templates
## 3  ¦--Fiddler2               
## 4  ¦   ¦--Captures           
## 5  ¦   ¦   ¦--Requests       
## 6  ¦   ¦   °--Responses      
## 7  ¦   °--Scripts            
## 8  °--Favorites              
## 9      °--Links

这篇关于R:深度嵌套列表中的递归函数:层次结构的访问级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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