R/matrix_apply.R

Defines functions matrix_apply_column

matrix_apply_column <- function(x, FUN, by = NULL) {
    if (inherits(by, "data.frame") && nrow(by) == nrow(x)) {
        x <- cbind(data.table::data.table(by), data.table::data.table(x))
        data.table::setDT(x)
        bycols <- colnames(by)
        x <- x[, lapply(.SD, FUN), keyby = bycols]
        cols <- setdiff(colnames(x), colnames(by))
        x <- x[, ..cols]
        x <- as.matrix(x)
        dimnames(x) <- NULL
    } else {
        x <- apply(x, MARGIN = 2, FUN = FUN, simplify = TRUE)
        if (is.null(dim(x))) {
            x <- matrix(x, nrow = 1)
        }
    }
    return(x)
}

Try the marginaleffects package in your browser

Any scripts or data that you put into this service are public.

marginaleffects documentation built on April 4, 2025, 4:36 a.m.