In tree, if I were to treat each list as a directory and each
non-list-object as a file, it would look like:
.
├── A
│ ├── Aa
│ │ ├── vec
│ │ ├── mat
│ │ ├── df
│ │ └── [[4]]
│ ├── Ab
│ │ ├── vec
│ │ ├── mat
│ │ ├── df
│ │ └── [[4]]
│ └── Ac
│ ├── vec
│ ├── mat
│ ├── df
│ └── [[4]]
├── B
│ ├── Ba
│ │ ├── vec
│ │ ├── mat
│ │ ├── df
│ │ └── [[4]]
│ ├── Bb
│ │ ├── vec
│ │ ├── mat
│ │ ├── df
│ │ └── [[4]]
│ └── Bc
│ ├── vec
│ ├── mat
│ ├── df
│ └── [[4]]
└── C
├── Ca
│ ├── vec
│ ├── mat
│ ├── df
│ └── [[4]]
├── Cb
│ ├── vec
│ ├── mat
│ ├── df
│ └── [[4]]
└── Cc
├── vec
├── mat
├── df
└── [[4]]
I wanted to replicate that in R. There is the default str()
command, which produces a really ugly looking list representation.
For things like .rmd reports it would be nice to have a tidier
output. The function below is far from finished, and probably isn't
written particularly well, but I got frustrated with the project.
Also in the meantime I found the {{data.tree}} package, which
contains FromListSimple(), which performs basically the same
functionality.
listTree <- function(x, rootName = NULL){
require(purrr)
# Function to check object is a real list
##' is.list wrongly identifies data.frame
isList <- function(x){
inherits(x, "list")
}
# Function to render one level of a tree
levelRender <- function(x){
x_names <- sapply(1:length(x), function(y){
ifelse(is.null(names(x)[y]), paste0("[[", y, "]]"),
names(x)[y])
})
In some ways my function is actually nicer. FromListSimple()
doesn't pick up on objects that aren't data frames, and the tree
structure isn't as compact. Additionally, if any list items are
unnamed, the function fails entirely.
To improve my function I would ideally want to physically link
parent tree branches with |, but I couldn't figure out how, I spent
far too much time on it.