r - Display names of column of recursive list as tree -
is there (built'in/easy) way recursively display names of interlinked list tree? (with possibly output similar tree shell command. )
for instance list x, 2 column , b, consiting in 2 subcolumn a1 , a2
nametree(x) x ├── │ ├── a1 │ └── a2 └── b names(x) display [1] "a" "b"
here recursive solution:
nametree <- function(x, prefix = "") if( is.list(x) ) for( in seq_along(x) ) { cat( prefix, names(x)[i], "\n", sep="" ) nametree(x[[i]], paste0(prefix, " ")) } x <- list(x = list( = list( a1=1:10, a2=1:10 ), b = 1:10 )) nametree(x) # x # # a1 # a2 # b displaying tree structure branches rather spaces trickier:
nametree <- function(x, prefix1 = "", prefix2 = "", prefix3 = "", prefix4 = "") if( is.list(x) ) for( in seq_along(x) ) { cat( if(i<length(x)) prefix1 else prefix3, names(x)[i], "\n", sep="" ) prefix <- if( i<length(x) ) prefix2 else prefix4 nametree( x[[i]], paste0(prefix, "├──"), paste0(prefix, "│ "), paste0(prefix, "└──"), paste0(prefix, " ") ) } nametree(x) # x # +--a # ¦ +--a1 # ¦ +--a2 # +--b # +--c # +--a # +--b
Comments
Post a Comment