Skip to content

Commit b486919

Browse files
committed
Refactor gg_partial function to normalize input as character for consistent binding and ensure proper factor levels in categorical data
1 parent a73627f commit b486919

1 file changed

Lines changed: 10 additions & 13 deletions

File tree

R/gg_partial.R

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -75,21 +75,12 @@ gg_partial <- function(part_dta,
7575
## ---- Categorical variable: few unique x values -------------------
7676
## VarPro works with logical or continuous only; factors are
7777
## one-hot encoded internally in the varPro call.
78-
## Normalize factors so ordered/regular factors bind cleanly later.
79-
x_factor <- if (is.factor(x_vals)) {
80-
factor(
81-
as.character(x_vals),
82-
levels = levels(x_vals),
83-
ordered = FALSE
84-
)
85-
} else {
86-
factor(x_vals,
87-
levels = unique(x_vals),
88-
ordered = FALSE)
89-
}
78+
## Normalize to character so bind_rows sees a consistent type; we'll
79+
## re-factor within each feature after stacking.
80+
x_chr <- as.character(x_vals)
9081

9182
plt.df <- dplyr::bind_cols(
92-
x = x_factor,
83+
x = x_chr,
9384
yhat = part_dta$plotthis[[feature]]$yhat
9485
)
9586
plt.df$name <- names(part_dta$plotthis)[[feature]]
@@ -104,6 +95,12 @@ gg_partial <- function(part_dta,
10495
categorical <- NA
10596
} else {
10697
categorical <- dplyr::bind_rows(cat_list)
98+
categorical <- dplyr::group_by(categorical, name)
99+
categorical <- dplyr::mutate(
100+
categorical,
101+
x = factor(x, levels = unique(x))
102+
)
103+
categorical <- dplyr::ungroup(categorical)
107104
}
108105
## Optionally attach a model label (useful when overlaying multiple forests)
109106
if (!is.null(model)) {

0 commit comments

Comments
 (0)