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 is
$a [1] 1 2 $b [1] 2 3 $c [1] 3 4
Is there a simple function to do this?
Combine lists in R Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.
The row binding operation in R creates a matrix that contains the number of rows specified. SImilarly, n number of arrays can be created. The cbind() operation is then applied which takes as arguments the array vectors. It creates a combined matrix where the merging takes place using columns.
To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.
If lists always have the same structure, as in the example, then a simpler solution is
mapply(c, first, second, SIMPLIFY=FALSE)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With