Skip to content

Commit

Permalink
extract covariate information in sp terms more safely
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-buerkner committed Jan 29, 2025
1 parent 89f3c86 commit 927b2c2
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions R/formula-sp.R
Original file line number Diff line number Diff line change
Expand Up @@ -444,9 +444,9 @@ frame_sp <- function(x, data) {

# extract information on covariates
# only non-zero covariates are relevant to consider
not_one <- apply(mm, 2, function(x) any(x != 1))
cumsum_not_one <- cumsum(not_one)
out$Ic <- ifelse(not_one, cumsum_not_one, 0)
has_covars <- attr(mm, "covars")
cumsum_covars <- cumsum(has_covars)
out$Ic <- ifelse(has_covars, cumsum_covars, 0)
class(out) <- spframe_class()
out
}
Expand Down Expand Up @@ -520,14 +520,16 @@ sp_model_matrix <- function(formula, data, types = all_sp_types(), ...) {
terms_replace <- terms_unique[grepl_expr(regex, terms_unique)]
dummies <- paste0("dummy", seq_along(terms_replace), "__")
data[dummies] <- list(1)
terms_comb <- rep(NA, length(terms_split))
terms_comb <- covars <- rep(NA, length(terms_split))
# loop over terms and add dummy variables
for (i in seq_along(terms_split)) {
replace_i <- grepl_expr(regex, terms_split[[i]])
terms_i_replace <- terms_split[[i]][replace_i]
dummies_i <- dummies[match(terms_i_replace, terms_replace)]
terms_split[[i]][replace_i] <- dummies_i
terms_comb[i] <- paste0(terms_split[[i]], collapse = ":")
# non-special covariates are part of the term
covars[i] <- !all(replace_i)
}
new_formula <- str2formula(terms_comb)
attributes(new_formula) <- attributes(formula)
Expand All @@ -536,6 +538,7 @@ sp_model_matrix <- function(formula, data, types = all_sp_types(), ...) {
colnames(out) <- rm_wsp(colnames(out))
# recover original column names
colnames(out) <- rename(colnames(out), dummies, terms_replace)
attr(out, "covars") <- covars
out
}

Expand Down

0 comments on commit 927b2c2

Please sign in to comment.