1

I have N lists that have some identical column names. Here is a MWE with two list:

ls <- list()
ls[[1]] <- list("a"=1:2,
                "b"=20,
                "c"=numeric(0))
names(ls[[1]]$a) <- c("a1", "a2")

ls[[2]] <- list("a"=3:4,
                "b"=30,
                "c"=1:4,
                "d"="f")
names(ls[[2]]$a) <- c("a1", "a2")

Is it possible merge these into a resulting list lsRes, where lsRes has the following properties:

  1. lsRes$a contains two elements, where the first is the named vector c(1,2) (with names c(a1, a2)) and the second a named vector c(3,4) (with names (c(a1.a2)))
  2. lsRes$b contains two elements, where the first is 20 and the second is 30

  3. lsRes$c contains two elements, where the first is numeric(0) and the second is 1:4

  4. lsRes$d contains two elements, where the first is NA and the second is "f"

I looked at this and this, but they describe different cases

N08
  • 1,265
  • 13
  • 23

1 Answers1

1

Assuming that we need to have the output also as a list, we create the common names and then assign those doesn't any of the common names to NA

nm1 <- unique(unlist(sapply(ls, names)))
lsRes <- lapply(ls, function(x) {x[setdiff(nm1, names(x))] <- NA; x})
lengths(lsRes)
#[1] 4 4

If we need to have a list of 4 elements, then use transpose

library(purrr)
lsRes %>%
      transpose
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks. but isn't `lsRes` identical to `ls`? – N08 Nov 14 '17 at 12:12
  • 1
    @N08 I has the additional element for 'd'. Do u want a list output or somethign else? – akrun Nov 14 '17 at 12:16
  • Thanks. Is it possible to merge the lists together now so the four conditions above are satisfied? – N08 Nov 14 '17 at 12:17
  • @N08 Do u need a data.frame as output? It is not clear about how the output would look like – akrun Nov 14 '17 at 12:18
  • Yes, a data.frame – N08 Nov 14 '17 at 12:19
  • For the `a`, there are 2 elements each for each list element, but 'b' have both single element, `c` with one element as numeric(0) etc. Can u show the expected output in your post – akrun Nov 14 '17 at 12:21
  • I tried to describe it with the numbered list in my OP. Should I elaborate? – N08 Nov 14 '17 at 12:23
  • @N08 Thanks, I read that part, but I am not sure how the output you wanted as a data.frame – akrun Nov 14 '17 at 12:25
  • it seems I can't convert it to a data.frame due to the following being illegal: `lsRes$a[[1]] = named vector c(1,2)`. Maybe a list is the way to go? – N08 Nov 14 '17 at 12:30
  • @N08 It is better to store it in a list, but it can be converted if you show what exactly you are expecting – akrun Nov 14 '17 at 12:31