Merge Two Lists in R

后端 未结 6 1109
南旧
南旧 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:31

    This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

    appendList <- function (x, val) 
    {
        stopifnot(is.list(x), is.list(val))
        xnames <- names(x)
        for (v in names(val)) {
            x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
                appendList(x[[v]], val[[v]])
            else c(x[[v]], val[[v]])
        }
        x
    }
    
    > appendList(first,second)
    $a
    [1] 1 2
    
    $b
    [1] 2 3
    
    $c
    [1] 3 4
    

提交回复
热议问题