Skip to content

Instantly share code, notes, and snippets.

@mikelove
Last active February 27, 2026 15:19
Show Gist options
  • Select an option

  • Save mikelove/92fc23d64ca0cf533ad8cdc096dd4811 to your computer and use it in GitHub Desktop.

Select an option

Save mikelove/92fc23d64ca0cf533ad8cdc096dd4811 to your computer and use it in GitHub Desktop.
Compact left_join.DataFrame
# adapted from DFplyr
# ignoring rownames and GroupedDataFrame functionality...
left_join.DataFrame <- function(x, y, by = NULL, ...) {
if (is.null(by)) {
by <- intersect(names(x), names(y))
if (length(by) == 0) {
rlang::abort("`by` must be supplied when `x` and `y` have no common variables.")
}
message("Joining with `by = ", deparse(by), "`")
}
S4Vectors::merge(x, y, by = by, sort = FALSE, ...)
}
@sa-lee
Copy link

sa-lee commented Feb 25, 2026

would something like this work if you just wanted to do a left join without introducing a dependency, you could wrap up the bit where you set up the join to be a helper function but I don't think you need to register a generic for it since you can let S4Vectors::merge handle dispatch?

join_mcols_left <- function(x, y, by = NULL, ...) {
    x_id <- x
    x_id$.id <- factor(seq_along(x))
    if (!is(y, "DataFrame")) {
        y <- DataFrame(y)
    }
    if (is.null(by)) {
        by <- intersect(names(mcols(x_id)), names(y))
        if (length(by) == 0) {
            rlang::abort("`by` must be supplied when `x` and `y` have no common variables.")
        }
        message("Joining with `by = ", deparse(by), "`")
    }
    new_mcols <- S4Vectors::merge(mcols(x_id), y, by = by, sort = FALSE, ...)
    new_mcols <- new_mcols[order(new_mcols$.id), ]
    new_x <- x[as.integer(new_mcols$.id)]
    new_mcols$.id <- NULL
    mcols(new_x) <- NULL
    mcols(new_x) <- new_mcols
    return(new_x)
}

@mikelove
Copy link
Author

thanks! I'll work on adding/testing this next week (my end of week got backed up with deadlines)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment