list_flatten with level and inner argument
I would like, if it is possible, to add an argument to list_flatten() where you can set the number of times the function will flatten a list. Instead of piping the list_flatten()multiple times, you can add a depthor level argument for how many levels it should flatten the list.
Also it would be nice to be able to set how to flatten the list, i.e. which levels to flatten first. This could be done with a inner = TRUE for example.
Levels of flattening
I have a complicated list with many levels that I want to flatten to the next simplest level.
complicated_list <- list(12, 2, 5, list("papaya", "kiwi"), list("banana", "apple", list("cow", "cat", list("lama", "alpaca"))))
complicated_list %>%
list_flatten() %>%
list_flatten() %>%
str()
List of 10
$ : num 12
$ : num 2
$ : num 5
$ : chr "papaya"
$ : chr "kiwi"
$ : chr "banana"
$ : chr "apple"
$ : chr "cow"
$ : chr "cat"
$ :List of 2
..$ : chr "lama"
..$ : chr "alpaca"
This is ok if it is only a couple of levels but instead of piping it would be neat to do:
complicated_list %>%
list_flatten(levels = 2) %>%
str()
List of 10
$ : num 12
$ : num 2
$ : num 5
$ : chr "papaya"
$ : chr "kiwi"
$ : chr "banana"
$ : chr "apple"
$ : chr "cow"
$ : chr "cat"
$ :List of 2
..$ : chr "lama"
..$ : chr "alpaca"
Inner flattening
However this leaves the fruit and animals mixed in one list and the some animals left in another list. I would like to be able to do:
complicated_list %>%
list_flatten(levels = 2, inner = T) %>%
str()
List of 8
$ : num 12
$ : num 2
$ : num 5
$ : chr "papaya"
$ : chr "kiwi"
$ : chr "banana"
$ : chr "apple"
$ :List of 4
..$ : chr "cow"
..$ : chr "cat"
..$ : chr "lama"
..$ : chr "alpaca"
I just wanted to set up this issue 😆 +1
Unfortunately list_flatten() is about as complicated as I want it to get. So unfortunately I don't think this is a good fit for purrr. But I appreciate the idea and thanks for using purrr!