Merge-sum, k-way merge

Open
#2,097 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
r
Domain
data

Research direction

The issue body is the only named starting point: review the rbindlist and Reduce examples and the requirement for sorted, keyed tables. The API and associative-reduction semantics still need definition; done should include the sample tables producing the expected result, with tests added, though no repository files or tests are named.

Written by the indexing model from the issue text.

Description

feature request joins

I have a pattern in several packages when "merge-sum" functionality would be super useful.
Imaging that I have several data.tables with same columns and same key. And I want to merge/aggregate them by key summing values:

dt1 = data.table(a = 1:5, b = 1:5, c = 1, key = c("a", "b"))
dt2 = data.table(a = 3:8, b = c(3:5, 8:6), c = 2, key = c("a", "b"))
dt3 = data.table(a = 7:8, b = c(7:8), c = 3, key = c("a", "b"))

At the moment I use following:

res = rbindlist(list(dt1, dt2, dt3))[, .(c = sum(c)), keyby = .(a, b)]
res
# a b c
# 1: 1 1 1
# 2: 2 2 1
# 3: 3 3 3
# 4: 4 4 3
# 5: 5 5 3
# 6: 6 8 2
# 7: 7 7 5
# 8: 8 6 2
# 9: 8 8 3

Alternative will be to use merge (but I found it less efficient):

res = Reduce(function(x, y) merge(x, y, all = TRUE)[is.na(c.x), c.x := 0][is.na(c.y), c.y := 0][, .(a, b, c = c.x + c.y)], 
       list(dt1, dt2, dt3))
res
# a b c
# 1: 1 1 1
# 2: 2 2 1
# 3: 3 3 3
# 4: 4 4 3
# 5: 5 5 3
# 6: 6 8 2
# 7: 7 7 5
# 8: 8 6 2
# 9: 8 8 3

I'm sure that this can be done much more efficiently since all tables already sorted, but rbindlist destructs this. Also it can be generalized with initial value for "reduce" and not only summation, but for any function with associative property.

Dominant language
R
Stars
3.9k
Forks
1.1k
Avg merge
14h 4m
Merged PRs (30d)
4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Rdatatable/data.table

All issues in Rdatatable/data.table

Similar issues

More R issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.