1

I have a list of lists (I think), so within each element of the list: res[[i]], I have another list, something like:

[[1]]

[[1]]$a

[[1]]$a$`1`
"aa" "bb" "cc"

[[1]]$a$`2`
"aa" "bb" "cc" "dd"

[[2]]

[[2]]$a

[[2]]$a$`1`
"aa" "bb" "cc"

[[2]]$a$`2`
"aa" "bb" "cc" "dd"

...

I would like to merge all the objects in a new list in which I only have something like:

"aa" "bb" "cc"

"aa" "bb" "cc" "dd"

"aa" "bb" "cc" "cc"

...

any idea???

Justin
  • 42,475
  • 9
  • 93
  • 111
user18441
  • 643
  • 1
  • 7
  • 15
  • Can you make a small reproducible example? http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Roman Luštrik Apr 04 '13 at 16:59

1 Answers1

3

It looks like you want a "flat" list. For this, you can use unlist with recursive = FALSE, but depending on how deep the list is, that might be tedious. Here's an example:

Your data:

myList <- list(list(a = list("1" = letters[1:3], "2" = letters[1:4])),
               list(a = list("1" = letters[1:3], "2" = letters[1:4])))
myList
# [[1]]
# [[1]]$a
# [[1]]$a$`1`
# [1] "a" "b" "c"
# 
# [[1]]$a$`2`
# [1] "a" "b" "c" "d"
# 
# 
# 
# [[2]]
# [[2]]$a
# [[2]]$a$`1`
# [1] "a" "b" "c"
# 
# [[2]]$a$`2`
# [1] "a" "b" "c" "d"

Using nested unlists:

unlist(unlist(myList, recursive=FALSE), recursive=FALSE)
# $a.1
# [1] "a" "b" "c"
# 
# $a.2
# [1] "a" "b" "c" "d"
# 
# $a.1
# [1] "a" "b" "c"
# 
# $a.2
# [1] "a" "b" "c" "d"

There is also this nifty function called LinearizeNestedList (https://sites.google.com/site/akhilsbehl/geekspace/articles/r/linearize_nested_lists_in_r) that can be downloaded/sourced in R and used as follows (for lists of any depth of nesting):

LinearizeNestedList(myList, NameSep=".")
# $`1.a.1`
# [1] "a" "b" "c"
# 
# $`1.a.2`
# [1] "a" "b" "c" "d"
# 
# $`2.a.1`
# [1] "a" "b" "c"
# 
# $`2.a.2`
# [1] "a" "b" "c" "d"

Edit

It appears this question is a duplicate of How to flatten a list to a list without coercion?

See that question and set of answers for other useful solutions.

Community
  • 1
  • 1
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485