I need to extract into a new column the number of observations per level from a Cox regression object. If I run:
res <- coxph(Surv(age, status) ~ score, data = df)
res %>% tbl_regression(exp = T) %>% add_n(location = 'level')
I get a similar table: Table (Credit)
Evidently, add_n() takes the number of observations from somewhere.
I looked at the object but I only saw where the total number of observations is stored, not per level. I googled but nothing relevant came up.
Answer provided by @AllanCameron in the comments:
The short answer is that it isn't stored inside the model. The number of obs per level is calculated inside tbl_regression, ultimately using broom.helpers:::model_get_n.coxph. It is stored as part of the table_body member of the tbl_regression output. It works via model.frame. You could do the same yourself quite easily by doing table(model.frame(res)[[2]])