Reproducible example:
require(survival)
require(finalfit)
require(ggplot2)
var0 <- sample(1:0, 100, replace = T)
var1 <- sample(c("A", "B", "C"), 100, replace = T)
var2 <- sample(c("X", "Y", "Z"), 100, replace = T)
var3 <- sample(500:2000, 100)
mydf <- data.frame(var0, var1, var2, var3)
dependent <- "Surv(time = var3, event = var0)"
varlist <- c("var1", "var2")
hrplots <- list()
for (i in varlist){
hrplots[[i]] <- hr_plot(mydf, dependent, i, table_text_size = 5)
}
The result is a list of two plots, the second of which is displayed, but I can't retrieve the first one as a visual, i.e. to display it. For example if I try: hrplots$var1
, I get
TableGrob (2 x 2) "arrange": 3 grobs
z cells name grob
1 1 (2-2,1-1) arrange gtable[layout]
2 2 (2-2,2-2) arrange gtable[layout]
3 3 (1-1,1-2) arrange text[GRID.text.1676]
I have tried print, show, even recordPlot and then replayPlot:
hrplots[[i]] <- recordPlot(hr_plot(mydf, dependent, i, table_text_size = 5))
But nothing seems to "bring back" the first plot as a visual. In my real data I have a great many plots that need to end up in an Rmd document, so I need to be able to display them. Does anyone know how to do this?
The objects stored in hrplots
are TableGrobs, which are a type of graphical object that is drawn with grid
graphics rather than base R graphics. To draw these objects as plots we can do:
grid::grid.newpage()
grid::grid.draw(hrplots[[1]])
and
grid::grid.newpage()
grid::grid.draw(hrplots[[2]])
Created on 2022-08-26 with reprex v2.0.2