Skip to content

Commit 4704076

Browse files
Check roll-on-factor up-front to simplify later checks (#6639)
* small refactor of bmerge() to check roll-on-factor condition first * restore factor checks as coming first --------- Co-authored-by: Benjamin Schwendinger <[email protected]>
1 parent 48cb609 commit 4704076

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

R/bmerge.R

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ coerce_col = function(dt, col, from_type, to_type, from_name, to_name, from_deta
2727

2828
bmerge = function(i, x, icols, xcols, roll, rollends, nomatch, mult, ops, verbose)
2929
{
30+
if (roll != 0.0 && length(icols)) {
31+
last_x_idx = tail(xcols, 1L)
32+
last_i_idx = tail(icols, 1L)
33+
if (is.factor(x[[last_x_idx]]) || is.factor(i[[last_i_idx]]))
34+
stopf("Attempting roll join on factor column when joining x.%s to i.%s. Only integer, double or character columns may be roll joined.", names(x)[last_x_idx], names(i)[last_i_idx])
35+
}
36+
3037
callersi = i
3138
i = shallow(i)
3239
# Just before the call to bmerge() in [.data.table there is a shallow() copy of i to prevent coercions here
@@ -64,9 +71,8 @@ bmerge = function(i, x, icols, xcols, roll, rollends, nomatch, mult, ops, verbos
6471
iname = paste0("i.", names(i)[icol])
6572
if (!x_merge_type %chin% supported) stopf("%s is type %s which is not supported by data.table join", xname, x_merge_type)
6673
if (!i_merge_type %chin% supported) stopf("%s is type %s which is not supported by data.table join", iname, i_merge_type)
74+
# we check factors first because they might have different levels
6775
if (x_merge_type=="factor" || i_merge_type=="factor") {
68-
if (roll!=0.0 && a==length(icols))
69-
stopf("Attempting roll join on factor column when joining %s to %s. Only integer, double or character columns may be roll joined.", xname, iname)
7076
if (x_merge_type=="factor" && i_merge_type=="factor") {
7177
if (verbose) catf("Matching %s factor levels to %s factor levels.\n", iname, xname)
7278
set(i, j=icol, value=chmatch(levels(i[[icol]]), levels(x[[xcol]]), nomatch=0L)[i[[icol]]]) # nomatch=0L otherwise a level that is missing would match to NA values
@@ -86,7 +92,6 @@ bmerge = function(i, x, icols, xcols, roll, rollends, nomatch, mult, ops, verbos
8692
}
8793
stopf("Incompatible join types: %s (%s) and %s (%s). Factor columns must join to factor or character columns.", xname, x_merge_type, iname, i_merge_type)
8894
}
89-
# we check factors first to cater for the case when trying to do rolling joins on factors
9095
if (x_merge_type == i_merge_type) {
9196
if (verbose) catf("%s has same type (%s) as %s. No coercion needed.\n", iname, x_merge_type, xname)
9297
next

0 commit comments

Comments
 (0)