How do I make a For-Loop for multiple plots to be saved in R

41 views Asked by At

I am trying to produce 7 plots. For the first I want all instances of "i" to be replaced by 0, then by 1, then by 2, and so on up to 6.

The code works when I manually replace all "i" by "2" for example but the For Loop doesn't seem to know where I want my variables. I tried using paste0 for some variables but then it got even more confusing for this beginner.

for (i in 0:6) {
PBL_s$time_thresh_i <- cut(PBL_s$time_12_5_tot_dup, breaks = c(-Inf, i, Inf),
                           labels = c("<=i","i"))

kmfit_thresh_i <- survfit(Surv(surv_time, event) ~ time_thresh_i,
                          data = PBL_s)

plot_i <- ggsurvplot(
  kmfit_thresh_i,
  data = PBL_s,
  las = 1,
  mark.time = TRUE,
  xlim = c(0, 84),
  break.time.by = 6,
  lwd = 1,
  ggtheme = theme_minimal(),
  risk.table = TRUE,
  pval = FALSE,
  legend.labs = c("less than i months", "more than i months"))

plot_i

png(file = "Time above cutoff KMs_i.png", width = 1119, height = 439)
print(plot_i)
dev.off()
}
0

There are 0 answers