Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flattening a list with unlist(), but keeping only the sublist names

I have a list in which each object is itself a list. I would like to flatten the list to one level, but keep the sublist names only, not prepend the higher level list name. I can use something like the example below, but I don’t know how to keep only the sublist names?

# Create a list of lists
my_list <- list(
  group1 = list(a = 1, b = 2),
  group2 = list(c = 3, d = 4)
)

# Flatten
flat_list <- unlist(my_list, recursive = FALSE)

The result is:

> flat_list
$group1.a
[1] 1

$group1.b
[1] 2

$group2.c
[1] 3

$group2.d
[1] 4

But I don’t want group1.a, I just want a.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use unname() to drop the names of the top-level list, before unlist()ing.

my_list |> 
  unname() |>
  unlist(FALSE)
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
#> 
#> $c
#> [1] 3
#> 
#> $d
#> [1] 4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading