Home > Software engineering >  How do you change the way unlist use.names structures the names it puts together
How do you change the way unlist use.names structures the names it puts together

Time:01-20

I've got a set of nested lists, such as this:

setoflists <- list(first.list = list(letter.a=1, letter.b=2, letter.c=3),
                   second.list = list(letter.d=4, letter.e=5, letter.f=6))

I want to flatten it to a single list. However, I want the names of the objects in the list to have the sublist first, then the top list, separated by an underscore "_". One reason is my list names already have lots of fullstops (.) in them.

I can flatten the list with unlist like so:

newlist <- unlist(setoflists, use.names = T, recursive = F)

but the names produced have top list, then sublist, separated by "."

> names(newlist)
[1] "first.list.letter.a"  "first.list.letter.b"  "first.list.letter.c"  "second.list.letter.d" "second.list.letter.e"
[6] "second.list.letter.f"

The format I want is:

letter.a_first.list
letter.b_first.list ...

CodePudding user response:

I don't think there's a way to control this using the current approach as it's calling make.names() as part of unlist(). You probably need to rename afterwards:

names(newlist) <- unlist(Map(paste, lapply(setoflists, names), names(setoflists), sep = "_"))

names(newlist)

[1] "letter.a_first.list"  "letter.b_first.list"  "letter.c_first.list"  "letter.d_second.list" "letter.e_second.list"
[6] "letter.f_second.list"

CodePudding user response:

One solution with regex, following the first idea of @ritchie-sacramento:

setoflists <- list(firstlist = list(letter.a=1, letter.b=2, letter.c=3),
                   secondlist = list(letter.d=4, letter.e=5, letter.f=6))

newlist <- unlist(setoflists, use.names = T, recursive = F)

names(newlist) <- sub("(.*)(?:[.])(letter. )", "\\2_\\1", names(newlist))

names(newlist)

Output:

> names(newlist)
[1] "letter.a_first.list" "letter.b_first.list" "letter.c_first.list" "letter.d_secondlist" "letter.e_secondlist" "letter.f_secondlist"
  • Related