Last active
January 8, 2020 10:48
-
-
Save Kumquatum/511053a27d92f1b037b0fbf583019ce9 to your computer and use it in GitHub Desktop.
Get list depth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Computes max depth of a list (recursively) | |
depth <- function(this) { | |
if (is.list(this)) { | |
ifelse(length(this) > 0, 1 + max(sapply(this, depth)), 0) | |
} else { 0 } | |
} | |
# Wrapping function to check if first point of entry is a list | |
list.depth <- function(my_list) { | |
ifelse(is.list(my_list), depth(my_list), stop("my_list have to be a list")) | |
} | |
## Inspired from https://stackoverflow.com/questions/13432863/determine-level-of-nesting-in-r#comment18364266_13433689 | |
## Modified for empty list handling and check on input | |
## Edit : depth function can be replaced by purrr::vec_depth. However it increments from 1 and not 0 like my depth function. | |
## So be carefull to adjust it (-1) or take it into account next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment