R中的情节列表结构

时间:2016-05-16 21:09:29

标签: r list graph structure

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

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)

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

2 个答案:

答案 0 :(得分:14)

您可以查看data.tree包裹。它允许很好地打印嵌套列表,它不需要你编写复杂的功能。这是一个例子:

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

这使您可以在列表级别进行检查,并且可以将其与str结合使用,以全面了解列表结构。

答案 1 :(得分:4)

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

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"

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