Creates, for each requested univariate smooth, a sequence over the range of the
smooth's numeric covariate, evaluates the term-wise contribution via
predict(fit, newdata = ., type = "terms") and stacks the results into a
tidy data frame.
get_terms(data, fit, terms = NULL, ...)A data frame containing variables used to fit the model. The first row is used as the basis for all covariates other than the one being varied (their values are irrelevant for the term-wise contribution).
A fitted object of class gam.
A character vector (can be length one) specifying the terms for
which partial effects will be returned. If NULL (the default) all
univariate smooth terms in the model are used.
Further arguments controlling extraction, passed on per term, e.g.
n (number of evaluation points) and conf_level.
A tibble with columns term, x, level, eff,
se, ci_lower and ci_upper.
For gam fits the requested terms are matched against
the model's smooths (see get_smooth_terms): a bare variable name
(e.g. "tend") selects every univariate smooth over that variable
– the main effect s(tend) as well as any s(tend, by = ...) or
factor-smooth interaction – while an exact smooth label (e.g. "s(tend)")
selects a single smooth. Names that do not match any smooth (for example
parametric factor main effects) are skipped with a warning; use
gg_fixed for those. For factor-indexed smooths one curve per
factor level is returned, identified by the level column.
For models without mgcv smooth metadata (e.g. coxph)
terms must be supplied and is matched against the columns of
predict(type = "terms").
library(survival)
fit <- coxph(Surv(time, status) ~ pspline(karno) + pspline(age), data=veteran)
terms_df <- veteran %>% get_terms(fit, terms = c("karno", "age"))
head(terms_df)
#> # A tibble: 6 × 7
#> term x level eff se ci_lower ci_upper
#> <chr> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 karno 10 NA 1.90 0.884 0.162 3.63
#> 2 karno 10.9 NA 1.89 0.822 0.276 3.50
#> 3 karno 11.8 NA 1.88 0.763 0.383 3.38
#> 4 karno 12.7 NA 1.87 0.707 0.483 3.25
#> 5 karno 13.6 NA 1.86 0.654 0.575 3.14
#> 6 karno 14.5 NA 1.84 0.604 0.658 3.03
tail(terms_df)
#> # A tibble: 6 × 7
#> term x level eff se ci_lower ci_upper
#> <chr> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 age 78.6 NA -0.166 0.712 -1.56 1.23
#> 2 age 79.1 NA -0.192 0.751 -1.66 1.28
#> 3 age 79.6 NA -0.219 0.793 -1.77 1.33
#> 4 age 80.1 NA -0.247 0.837 -1.89 1.39
#> 5 age 80.5 NA -0.275 0.884 -2.01 1.46
#> 6 age 81 NA -0.303 0.933 -2.13 1.52