Reshape a DALEX-like long SHAP table to wide format
Source:R/assert_data_table_available.R
dot-dalex_shap_to_wide.RdConvert a long-format SHAP table with observation IDs, feature names, and SHAP values to a wide format with one row per observation and one column per feature. Baseline rows can be optionally dropped based on common baseline labels.
Usage
.dalex_shap_to_wide(
shap,
id_col = NULL,
variable_col = NULL,
value_col = NULL,
drop_baseline = TRUE,
baseline_labels = c("_baseline_", "baseline", "intercept")
)Arguments
- shap
A long-format SHAP table containing observation IDs, feature names, and SHAP values.
- id_col
Optional column name identifying observations. If
NULL, common ID column names will be searched for.- variable_col
Optional column name containing feature names. If
NULL, common variable column names will be searched for.- value_col
Optional column name containing SHAP values. If
NULL, common value column names will be searched for.- drop_baseline
Logical scalar. If
TRUE, rows with feature names matching common baseline labels will be dropped before reshaping.- baseline_labels
Character vector of feature names to treat as baseline rows when
drop_baseline = TRUE. Matching is case-sensitive.
Value
A wide-format data.table with one row per observation and one
numeric column per SHAP feature. Rows follow the first appearance of each
observation ID in shap, and the observation IDs are returned in that
order as the "observation_ids" attribute so callers can align other
per-observation inputs.
Details
The function attempts to identify the ID, variable, and value
columns based on common naming conventions. If drop_baseline = TRUE,
rows with feature names in baseline_labels are removed before
reshaping. The resulting wide table contains only numeric SHAP feature
columns. Row order is preserved rather than sorted by ID, because sorting
would silently detach the SHAP rows from separately supplied ranks,
weights or predictions. Duplicate observation-feature pairs are rejected
instead of being counted by dcast(). Aliases for the identified columns
are as follows:
ID column candidates:
"_id_","id","row_id","observation_id","observation","case_id"Variable column candidates:
"_vname_","variable","variable_name","feature"Value column candidates:
"_attribution_","contribution","phi","shap","value"