You can fit a Cox model that relaxes the linearity assumption for the risk_factor
on the log hazard scale, using, e.g., splines. You could compare this model with the linear fit using a likelihood ratio test and see if the effect is linear or not. If it is nonlinear, you can depict with an effects plot.
The code below illustrates these steps with your simulated data:
library("survival")
library("lattice")
library("splines")
# simulate the data
timespan_censored <- c(round(runif(450, 0, 4500), digit = 0),
round(runif(150, 0, 1200), digit = 0))
risk_factor <- c(runif(450, min = 10, max = 80),
runif(150, min = 20, max = 100))
status <- c(rep(0, 450), rep(1, 150))
timespan_censored <- c(round(runif(450, 0, 4500), digit = 0),
round(runif(150, 0, 1200), digit = 0))
df_try <- data.frame(status, timespan_censored, risk_factor)
# fit a Cox model with a linear effect for 'risk_factor'
cox_mod1 <- coxph(Surv(timespan_censored, status) ~ risk_factor, data = df_try)
# fit a Cox model with a nonlinear effect for 'risk_factor' using natural cubic splines
cox_mod2 <- coxph(Surv(timespan_censored, status) ~ ns(risk_factor, 4), data = df_try)
# likelihood ratio test for linearity
anova(cox_mod1, cox_mod2)
# Create an effect plot to depict the relationship
ND <- with(df_try, data.frame(risk_factor = seq(min(risk_factor),
max(risk_factor), length.out = 500)))
prs <- predict(cox_mod2, newdata = ND, type = "lp", se.fit = TRUE)
ND$pred <- prs[[1]]
ND$se <- prs[[2]]
ND$lo <- ND$pred - 1.96 * ND$se
ND$up <- ND$pred + 1.96 * ND$se
xyplot(pred + lo + up ~ risk_factor, data = ND,
type = "l", col = "black", lwd = 2, lty = c(1, 2, 2),
abline = list(h = 0, lty = 2, lwd = 2, col = "red"),
xlab = "Risk Factor", ylab = "log Hazard Ratio")
You can find more examples in my Survival Analysis in R Companion for my survival course.