#------package------
library(survival)
#-------------------
#------some data------
data(kidney)
#---------------------
#------preparation------
tab <- data.frame(table(kidney[kidney$status == 1, "time"]))
y <- as.numeric(levels(tab[, 1]))[tab[, 1]] #ordered distinct event times
d <- tab[, 2] #number of events
#-----------------------
#------Cox model------
fit<-coxph(Surv(time, status)~age, data=kidney)
#---------------------
#------cumulative hazard obtained from basehaz()------
H0 <- basehaz(fit, centered=FALSE)
H0 <- H0[H0[, 2] %in% y, ] #only keep rows where events occurred
#-----------------------------------------------------
#------my quick implementation------
betaHat <- fit$coef
h0 <- rep(NA, length(y))
for(l in 1:length(y))
{
h0[l] <- d[l] / sum(exp(kidney[kidney$time >= y[l], "age"] * betaHat))
}
#-----------------------------------
#------comparison------
cbind(H0, cumsum(h0))
#----------------------