1

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()
}
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
  • Presumably one would add each plot to an indexed object (which I so not see being done here) and than print the assembly. Pretty sure this has been asked and answered on SO. (The "medical" tag appears irrelevant.) – IRTFM Jun 13 '23 at 02:16
  • 1
    Thanks IRTFM, how does one "add each plot to an indexed object". Also, feel free to actually link where you say this has been asked and answered to substantiate your claim. – Benjamin Trewin Jun 13 '23 at 03:26
  • 1
    So you are saying you reviewed the completely obvious search strategy: https://stackoverflow.com/search?q=%5Br%5D+ggplot.+Multiple+plots+%5Bfor-loop%5D ? It’s not my responsibility to do the search and review the results. It’s your responsibility to review them and say what you tried from similar prior posts and how they failed. – IRTFM Jun 13 '23 at 06:18
  • 1
    Surprisingly your problem has little to do with plotting directly. It's about how you access your `i` variable in a string. Currently all your plots will be saved to the same file, `"Time above cutoff KMs_i.png"`, rather than `i` being replaced by the index. Search R string interpolation, or check out the answers [here](https://stackoverflow.com/questions/70754075/for-loop-to-read-multiple-csv-files-in-r-from-different-directories/70754185#70754185) and [here](https://stackoverflow.com/questions/70754075/for-loop-to-read-multiple-csv-files-in-r-from-different-directories/70754185#70754185). – SamR Jun 13 '23 at 06:51
  • 1
    Apologies both of those links are the same - the first one explains why what you're doing doesn't work, but the second should have been [how to make it work](https://stackoverflow.com/questions/74277613/remove-space-from-paste-above-array-in-r/74278086#74278086). – SamR Jun 13 '23 at 08:39

0 Answers0