Skip to content

Instantly share code, notes, and snippets.

@Dpananos
Created June 17, 2023 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dpananos/a46c33ca321bfc50e03b9863ab18fc70 to your computer and use it in GitHub Desktop.
Save Dpananos/a46c33ca321bfc50e03b9863ab18fc70 to your computer and use it in GitHub Desktop.
Marginal effect for cox model
library(survival)
library(tidyverse)
library(broom)
library(marginaleffects)
# Make a toy model
gr <- sample(letters[1:2], size = 10000, replace=T)
g <- as.numeric(gr=='a')
etime <- rexp(length(gr), rate = (5+1*g)/10)
d <- tibble(gr, etime, event=1)
# Fit the cox model
fit <- coxph(Surv(etime, event) ~ gr, data=d)
# Estimate surival times myself
b<-map_dfr(c('a','b'), ~{
survfit(fit,
newdata = tibble(gr=.x)) %>%
tidy %>%
mutate(gr=.x)
})
# Difference in survival times by hand
bb <-b %>%
select(time, gr, estimate) %>%
pivot_wider(id_cols=time, names_from = gr, values_from = estimate) %>%
mutate(delta = b-a)
bb %>%
ggplot(aes(time, delta)) +
geom_line()
# Looks pretty close!
plot_comparisons(fit,
variables = 'gr', by='etime', type='survival')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment