Skip to content

Merge function #322

@1danjordan

Description

@1danjordan

Saw this on HN today. The post is about the various methods of merging Maps (Dicts/Tables/...) in different languages. I especially liked the Clojure merge-with implementation.

In R, with identically sized lists A and B, Map(c, A, B) is a simple solution, or in purrr pmap(list(A, B), c).

Once the lists become more complicated, or the type of merge logic changes, this becomes much more complicated. For example, we might want to merge by name (key), position or just pack all elements together individually:

  A <- list(a = 1, b = "abc")
  B <- list(a = 2, b = "def", c = 1:5)
  C <- list(c = 6:10)

merge(list(A, B), .by = "name")
# => list(a = c(1, 2), b = c("abc", "def"), c = 1:5)

merge(list(A, C), .by = "position")
# => list(c(1, 6:10))
#          ^ strip names

merge(list(A, B, C))
# => list(a = 1, b = "abc", a = 2, b = "def", c = 1:5, c =  6:10)
# this is the same as flatten(list(A, B, C))

I figured there might be a place in purrr for merge.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions