Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

list_flatten with level and inner argument #1175

Open
ScientiaFelis opened this issue Mar 13, 2025 · 0 comments
Open

list_flatten with level and inner argument #1175

ScientiaFelis opened this issue Mar 13, 2025 · 0 comments

Comments

@ScientiaFelis
Copy link

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant