Search code examples
rlistflatten

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.


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