Let's say I have a "kidney catheter" data set. I'm trying to model a survival curve using a Cox model. If I consider a Cox model: $$h(t,Z) = h_0 \exp(b'Z),$$ I need the estimate of the baseline hazard. By using the built-in survival
package R function basehaz()
, I can easily do it like this:
library(survival)
data(kidney)
fit <- coxph(Surv(time, status) ~ age , kidney)
basehaz(fit)
But if I want to write a step by step function of the baseline hazard for a given estimate of parameter b
how can I proceed? I tried:
bhaz <- function(beta, time, status, x) {
data <- data.frame(time,status,x)
data <- data[order(data$time), ]
dt <- data$time
k <- length(dt)
risk <- exp(data.matrix(data[,-c(1:2)]) %*% beta)
h <- rep(0,k)
for(i in 1:k) {
h[i] <- data$status[data$time==dt[i]] / sum(risk[data$time>=dt[i]])
}
return(data.frame(h, dt))
}
h0 <- bhaz(fit$coef, kidney$time, kidney$status, kidney$age)
But this does not give the same result as basehaz(fit)
. What is the problem?