library(survival)
library(pROC)
# Create random x (predictors) and y (survival)
x = matrix(rnorm(5000), ncol = 10)
time = rexp(500)
y = Surv(time, plogis(x[,1] / pmax(1, time^2) + rnorm(500)) > 0.5)
# Predict y via cross-validation
fit_fun = function (x, y) {
glmnet_fit(x, y, family = "cox")
}
predict_fun = function (m, x) {
glmnet_predict(m, x)
}
res = cv(x, y, family = "cox", fit_fun = fit_fun, predict_fun = predict_fun)
# Convert y to binary
y.binary = surv2binary(y)
# Calculate and plot AUC for binary y at each timepoint
time_auc = NULL
for (i in 1:length(y.binary)) {
status_i = y.binary[[i]]$status
if (length(unique(na.omit(status_i))) == 2) {
time_auc = rbind(time_auc, data.frame(
time = y.binary[[i]]$time,
auc = roc(status_i ~ res$predictions$y.pred, levels = 0:1, direction = "<")$auc
))
}
}
plot(time_auc$time, time_auc$auc, type = "l", xlab = "Time", ylab = "AUC", ylim = 0:1)
abline(h = 0.5)
Run the code above in your browser using DataLab