Pernii
Pernii

Reputation: 31

Unlisting a list of list while keeping second list names

I would like to unlist a list of list while keeping the names of the second list.

For example if have a list like this:

$`listA`  
  $`listA_a`
    [1] 1 2
  $`listA_g`
    [1] 1 2    
$`listB`  
  $`listB_b`
    [1] 1 2

I would like to obtain this list:

$`listA_a`
  [1] 1 2
$`listA_g`
  [1] 1 2    
$`listB_b`
  [1] 1 2

I know there is an argument in unlist to keep names (use.names = T, which is true by default) however it keeps the names of the first list and add a number if there is several elements ("listA1", "listA2", "listB").

(This is an example but in my code the elements of the list are plots so I cannot use a data.frame or anything... I cannot easily reconstruct the names as they contain informations about the data used for the plots).

Thank you very much for your help!

Pernille

Upvotes: 3

Views: 100

Answers (4)

akrun
akrun

Reputation: 887128

We could use rrapply from rrapply

library(rrapply)
rrapply(List, how = 'flatten')
#$listA_a
#[1] 1 2

#$listA_g
#[1] 1 2

#$listB_b
#[1] 1 2

data

List <- list(listA = list(listA_a = c(1, 2), listA_g = c(1, 2)), listB = list(
  listB_b = c(1, 2)))

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101393

Another option is using flatten from package purrr

> purrr::flatten(lst)
$listA_a
[1] 1 2

$listA_g
[1] 1 2

$listB_b
[1] 1 2

Upvotes: 0

Duck
Duck

Reputation: 39595

Try this approach. You can use unlist() with recursive=F to keep the desired structure and then format the names. Here the code:

#Data
List <- list(listA = list(listA_a = c(1, 2), listA_g = c(1, 2)), listB = list(
  listB_b = c(1, 2)))
#Code
L <- unlist(List,recursive = F)
names(L) <- gsub(".*\\.","", names(L) )
L

Output:

L
$listA_a
[1] 1 2

$listA_g
[1] 1 2

$listB_b
[1] 1 2

Or the more simplified version without regex (Many thanks and credits to @markus):

#Code 2
L <- unlist(unname(List),recursive = F)

Output:

L
$listA_a
[1] 1 2

$listA_g
[1] 1 2

$listB_b
[1] 1 2

Upvotes: 3

stefan
stefan

Reputation: 124183

Another option would be to make use of e.g. Reduce to concatenate the sublists:

list_of_lists <- list(
  listA = list(listA_a = c(1, 2), listA_g = c(1, 2)), 
  listB = list(listB_b = c(1, 2)
))
Reduce(c, list_of_lists)
#> $listA_a
#> [1] 1 2
#> 
#> $listA_g
#> [1] 1 2
#> 
#> $listB_b
#> [1] 1 2

Upvotes: 0

Related Questions