R/utils.R

Defines functions do_call warn_sprintf stop_sprintf stop_deprecate ...mget ...get group_to_factor sub_named_vector is_binary merge_original_data as_data_table_select cjdt finalize_estimates sanitize_inferences_method drop_trivial_group main_marginaleffect_group warn_once get_unique_index

get_unique_index <- function(x, term_only = FALSE) {
    idx <- c("term", "contrast", grep("^contrast_", colnames(x), value = TRUE))
    idx <- intersect(unique(idx), colnames(x))
    if (length(idx) == 0) {
        return(NULL)
    }
    if (length(idx) == 1) {
        return(x[[idx]])
    }
    out <- x[, idx, drop = FALSE]
    for (i in ncol(out):2) {
        if (length(unique(out[[i]])) == 1) {
            out[[i]] <- NULL
        }
    }
    out <- do.call(paste, c(as.list(out), sep = ", "))
    return(out)
}


warn_once <- function(msg, id) {
    if (!isTRUE(getOption(id, default = TRUE)) || !isTRUE(getOption("marginaleffects_safe", default = TRUE))) {
        return(invisible())
    }
    msg <- paste(msg, "This warning appears once per session.")
    # warn_sprintf(msg, call. = FALSE)
    warning(msg, call. = FALSE)
    opts <- list(FALSE)
    names(opts) <- id
    options(opts)
}

main_marginaleffect_group <- function() {
    "main_marginaleffect"
}


drop_trivial_group <- function(x) {
    if ("group" %in% names(x) && all(x$group == main_marginaleffect_group())) {
        x$group <- NULL
    }
    return(x)
}


sanitize_inferences_method <- function(vcov) {
    methods <- c("rsample", "boot", "fwb", "simulation")
    if (isTRUE(checkmate::check_choice(vcov, methods))) {
        list(vcov = FALSE, method = vcov)
    } else {
        list(vcov = vcov, method = NULL)
    }
}


finalize_estimates <- function(
    out,
    mfx,
    by,
    transform,
    equivalence,
    class_name,
    inferences_method = NULL,
    drop_group = FALSE,
    conf_int = TRUE,
    pre_transform = NULL,
    ...) {
    if (isTRUE(conf_int)) {
        out <- get_ci(out, mfx)
    }

    out <- sort_columns(out, mfx@newdata, by)
    out <- equivalence(out, equivalence = equivalence, df = mfx@df, draws = mfx@draws, ...)
    estimate_pre_transform <- out[["estimate"]]
    out <- backtransform(out, transform = pre_transform, draws = mfx@draws)
    mfx <- update_unconditional_vcov_transform(mfx, estimate_pre_transform, pre_transform)

    estimate_pre_transform <- out[["estimate"]]
    out <- backtransform(out, transform = transform, draws = mfx@draws)
    mfx <- update_unconditional_vcov_transform(mfx, estimate_pre_transform, transform)

    new_draws <- attr(out, "posterior_draws")
    if (!is.null(new_draws)) {
        mfx@draws <- new_draws
    }

    out[["marginaleffects_wts_internal"]] <- NULL
    data.table::setDF(out)
    class(out) <- c(class_name, class(out))

    if (inherits(mfx@model, "brmsfit")) {
        insight::check_if_installed("brms")
        mfx@draws_chains <- brms::nchains(mfx@model)
    }

    out <- add_attributes(out, mfx)
    out <- prune_attributes(out)

    if (isTRUE(drop_group)) {
        out <- drop_trivial_group(out)
    }

    if (!is.null(inferences_method)) {
        out <- inferences(out, method = inferences_method)
    }

    return(out)
}


# Cross join a list of data tables
# Source: https://github.com/Rdatatable/data.table/issues/1717#issuecomment-545758165
cjdt <- function(dtlist) {
    Reduce(
        function(DT1, DT2) cbind(DT1, DT2[rep(seq_len(.N), each = nrow(DT1))]),
        dtlist
    )
}


as_data_table_select <- function(x, cols) {
    if (data.table::is.data.table(x)) {
        x[, ..cols]
    } else {
        data.table::as.data.table(x[, cols, drop = FALSE])
    }
}


merge_original_data <- function(
    out,
    original,
    by = FALSE,
    keys = "rowid",
    payload = NULL,
    deduplicate = FALSE,
    unit_level_only = TRUE) {
    # Aggregated results do not map one-to-one to the original data.
    if (isTRUE(unit_level_only) && !isFALSE(by)) {
        return(out)
    }

    if (is.null(payload)) {
        payload <- setdiff(colnames(original), colnames(out))
    } else {
        payload <- setdiff(payload, colnames(out))
    }
    payload <- intersect(payload, colnames(original))
    if (length(payload) == 0) {
        return(out)
    }

    cols <- intersect(unique(c(keys, payload)), colnames(original))
    tmp <- as_data_table_select(original, cols)
    bycols <- intersect(colnames(tmp), colnames(out))
    if (!"rowid" %in% bycols || length(bycols) == 0) {
        return(out)
    }

    # Unit-level predictions usually preserve exact key order. Avoid a full
    # duplicate scan and join when the payload can be attached positionally.
    if (
        !isTRUE(deduplicate) &&
            nrow(out) == nrow(tmp) &&
            all(vapply(bycols, function(col) identical(out[[col]], tmp[[col]]), logical(1)))
    ) {
        return(cbind(out, tmp[, ..payload]))
    }

    if (isTRUE(deduplicate)) {
        idx <- duplicated(tmp, by = bycols)
        tmp <- tmp[!idx]
    } else if (any(duplicated(tmp, by = bycols))) {
        if ("rowid" %in% bycols && nrow(tmp) != nrow(out)) {
            tmp <- tmp[rowid %in% out[["rowid"]]]
        }
        outkeys <- as_data_table_select(out, bycols)
        tmpkeys <- tmp[, ..bycols]
        if (nrow(outkeys) == nrow(tmpkeys) &&
            isTRUE(all.equal(outkeys, tmpkeys, check.attributes = FALSE))) {
            return(cbind(out, tmp[, ..payload]))
        }
        return(out)
    }

    merge(out, tmp, all.x = TRUE, by = bycols, sort = FALSE)
}

# faster than all(x %in% 0:1)
is_binary <- function(x) {
    isTRUE(checkmate::check_integerish(
        x,
        null.ok = TRUE,
        upper = 1,
        lower = 0,
        any.missing = TRUE,
        all.missing = FALSE
    ))
}


sub_named_vector <- function(x, y) {
    # issue 1005
    xlab <- gsub("^`|`$", "", names(x))
    ylab <- gsub("^`|`$", "", names(y))

    idx <- match(ylab, xlab)
    if (length(stats::na.omit(idx)) > 0) {
        x[stats::na.omit(idx)] <- y[!is.na(idx)]
    } else if (length(y) == length(x)) {
        return(y)
    } else {
        stop(
            "set_coef() substitution error. Please report on Github with a reproducible example: https://github.com/vincentarelbundock/marginaleffects/issues",
            call. = FALSE
        )
    }

    return(x)
}


group_to_factor <- function(group, model) {
    dv <- try(insight::get_response(model), silent = TRUE)
    if (inherits(dv, "factor")) {
        if (length(unique(group)) == nlevels(dv)) {
            group <- factor(group, levels(dv))
        }
    }
    return(group)
}


...get <- function(x, ifnotfound = NULL) {
    eval(
        quote(
            if (!anyNA(.m1 <- match(.x, ...names())) && !is.null(.m2 <- ...elt(.m1))) {
                .m2
            } else {
                .ifnotfound
            }),
        pairlist(.x = x[1L], .ifnotfound = ifnotfound),
        parent.frame(1L)
    )
}


...mget <- function(x) {
    found <- match(x, eval(quote(...names()), parent.frame(1L)))
    not_found <- is.na(found)
    if (all(not_found)) {
        return(list())
    }
    stats::setNames(
        lapply(found[!not_found], function(z) {
            eval(
                quote(...elt(.z)),
                pairlist(.z = z),
                parent.frame(3L)
            )
        }),
        x[!not_found]
    )
}

stop_deprecate <- function(old, new = NULL) {
    if (is.null(new)) {
        msg <- sprintf("The `%s` argument is not supported.", old)
    } else {
        msg <- sprintf("The `%s` argument is not supported. Please use `%s` instead.", old, new)
    }
    stop(msg, call. = FALSE)
}


stop_sprintf <- function(msg, ...) {
    dots <- list(...)
    if (length(dots) > 0) {
        msg <- sprintf(msg, ...)
    }
    stop(msg, call. = FALSE)
}


warn_sprintf <- function(msg, ...) {
    if (!isTRUE(getOption("marginaleffects_safe", default = TRUE))) {
        return(invisible())
    }
    dots <- list(...)
    if (length(dots) > 0) {
        msg <- sprintf(msg, ...)
    }
    warning(msg, call. = FALSE)
}


# Like do.call() but avoids inlining argument values into the call expression.
# When do.call(fn, list(huge_model, huge_data)) errors, R stores the entire
# inlined data in sys.calls(), and IDEs (RStudio/Positron) try to deparse it,
# causing multi-minute hangs. This builds a call with symbol references instead.
# See: https://github.com/vincentarelbundock/marginaleffects/issues/1663
do_call <- function(what, args) {
    call_env <- new.env(parent = parent.frame())
    call_env[[".what"]] <- what
    arg_names <- names(args) %||% rep("", length(args))
    call_list <- vector("list", length(args) + 1L)
    call_list[[1L]] <- as.symbol(".what")
    for (i in seq_along(args)) {
        sym_name <- sprintf(".arg%d", i)
        call_env[[sym_name]] <- args[[i]]
        call_list[[i + 1L]] <- as.symbol(sym_name)
    }
    names(call_list) <- c("", arg_names)
    eval(as.call(call_list), call_env)
}

Try the marginaleffects package in your browser

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

marginaleffects documentation built on Sept. 3, 2026, 9:08 a.m.