Skip to content
Prev 247052 / 398503 Next

list concatenation

Hi Georg,

This was an interesting challenge to me.  Here's what I came up with.
The first option meets your desired result, but could get messy with
deeper nesting.  The second is less code, but is not quite what you
want and requires as.data.frame() to give a reasonable result for each
list.  Calling either option a "good solution" would be rather
generous.  I'm iinterested to see what other people do.

Josh

## Data
list.1 <- list("I"=list("A"=c("a", "b", "c"), "B"=c("d", "e", "f")),
              "II"=list("A"=c("g", "h", "i"), "B"=c("j", "k", "l")))
list.2 <- list("I"=list("A"=c("A", "B", "C"), "B"=c("D", "E", "F")),
              "II"=list("A"=c("G", "H", "I"), "B"=c("J", "K", "L")))

## Try 1
list.t1 <- list.1

for(i in length(list.1)) {
  for(j in length(list.1[[i]])) {
    list.t1[[c(i, j)]] <- c(list.1[[c(i, j)]], list.2[[c(i, j)]])
  }
}

## Try 2
list.t2 <- as.list(do.call("rbind", lapply(list(list.1, list.2),
  as.data.frame, stringsAsFactors = FALSE)))

## Results

list.t1
list.t2
On Tue, Jan 11, 2011 at 7:44 AM, Georg Otto <gwo at well.ox.ac.uk> wrote: