Merge Two Lists in R

后端 未结 6 1077
南旧
南旧 2020-11-28 22:52

I have two lists

first = list(a = 1, b = 2, c = 3)
second = list(a = 2, b = 3, c = 4)

I want to merge these two lists so the final product

6条回答
  •  清酒与你
    2020-11-28 23:30

    Here are two options, the first:

    both <- list(first, second)
    n <- unique(unlist(lapply(both, names)))
    names(n) <- n
    lapply(n, function(ni) unlist(lapply(both, `[[`, ni)))
    

    and the second, which works only if they have the same structure:

    apply(cbind(first, second),1,function(x) unname(unlist(x)))
    

    Both give the desired result.

提交回复
热议问题