Reputation: 7840
I have a list of vectors and sub-lists and I would like to unlist the sub-lists to get a list of vectors only.
my.list <- list(a = 1,
li1 = list(b = 2, c = 3),
li2 = list(d = 4, e = 5))
> my.list
$a
[1] 1
$li1
$li1$b
[1] 2
$li1$c
[1] 3
$li2
$li2$d
[1] 4
$li2$e
[1] 5
> unlist(my.list, recursive = FALSE)
$a
[1] 1
$li1.b
[1] 2
$li1.c
[1] 3
$li2.d
[1] 4
$li2.e
[1] 5
The simple way is to use unlist
with recursive = FALSE
but as you can see sub-list names are appended to the new elements names. And if I use use.names = FALSE
the entire element name is removed.
Is there a simple way to keep element names but remove appended alias ?
Thank for any help.
Upvotes: 4
Views: 427
Reputation: 13122
You could, also, remove the "names" of sub-lists recursively and, then, unlist
:
ff = function(x)
{
if(is.list(x)) {
names(x)[sapply(x, is.list)] = ""
lapply(x, ff)
} else return(x)
}
unlist(ff(my.list))
#a b c d e
#1 2 3 4 5
And on a more nested "list":
my.list2 = list(a = 1,
li1 = list(b = 2, c = 3),
li2 = list(li2a = list(d = 4, e = 5),
li2b = list(li2b1 = list(f = 6, g = 7),
li2b2 = list(h = 8),
li2b3 = list(li2b3a = list(i = 9, j = 10, k = 11)))))
unlist(ff(my.list2))
# a b c d e f g h i j k
# 1 2 3 4 5 6 7 8 9 10 11
Upvotes: 0