R中的绘图列表结构



我越来越多地使用高度嵌套的列表,例如:

mynestedlist<-list(list(LETTERS,month.name),list(list(seq(1,100,5),1,1),seq(1,100,5),seq(1,100,5)))

有时我很难理解我正在处理的列表的结构。我想知道是否有任何方法可以显示列表的层次结构,也许可以使用树状图。

我知道我可以使用str打印列表的结构:

str(mynestedlist,max.level=1)

但是,以图形方式显示列表会更有用!

您可以检查data.tree包。它可以很好地打印嵌套列表,而且不需要编写复杂的函数。这里有一个例子:

library(data.tree)
> dt <- FromListSimple(mynestedlist)
> dt
  levelName
1 Root     
2  ¦--1    
3  °--2    
4      °--1

这允许您在列表级别进行检查,您可以将其与str相结合,以获得列表结构的全貌。

如果你想的话,你也可以做一些漂亮的递归:

get_str_recur <- function(x,text2,y){
  text <- paste0(text2,"Element[",y,"] is a List of length ",length(x), " --> ")
  for (i in (1:(length(x)))){
    subs <- x[[i]]
    if (is.list(subs)){
      get_str_recur(subs,text,i)
    }else{
      print(paste0(text," Element [",i,"] is a ",class(subs)," of length ",length(subs)))
    }
  }
}
get_str_recur(mynestedlist,"",0)
#[1] "Element[0] is a List of length 2 --> Element[1] is a List of length 2 --#>  Element [1] is a character of length 26"
#[1] "Element[0] is a List of length 2 --> Element[1] is a List of length 2 -->  #Element [2] is a character of length 12"
#[1] "Element[0] is a List of length 2 --> Element[2] is a List of length 3 --> #Element[1] is a List of length 3 -->  Element [1] is a numeric of length 20"
#[1] "Element[0] is a List of length 2 --> Element[2] is a List of length 3 --> #Element[1] is a List of length 3 -->  Element [2] is a numeric of length 1"
#[1] "Element[0] is a List of length 2 --> Element[2] is a List of length 3 --> #Element[1] is a List of length 3 -->  Element [3] is a numeric of length 1"
#[1] "Element[0] is a List of length 2 --> Element[2] is a List of length 3 -->  #Element [2] is a numeric of length 20"
#[1] "Element[0] is a List of length 2 --> Element[2] is a List of length 3 -->  #Element [3] is a numeric of length 20"

这为列表树的每个分支提供了一个很好的可视化流程图。

最新更新