Xander Xander - 2 months ago 15
R Question

Producing ggplots from a loop (and generating the files) without printing any visible output in RMarkdown

I am building a table with a mixture of numbers, text, and plots. I constructed my plots with ggplot, and added them to the table afterwards (please see code below). Because I will (eventually) have many plots, I need to use a loop to efficiently create them all. However, because ggplot seems to require printing to generate image links for each plot, I am unable to use

invisible()
, and subsequently get the pesky '[1] [[2]] [[3]]' output at the top of the image below.

How can I compile the document without printing any visible output from ggplot?

```{r score_table, fig.show = "hide", echo = FALSE, fig.height=.75, fig.width=2.5}

#Load libraries
library(knitr)
library(ggplot2)

#Item data
items <- data.frame(text = sapply(1:3, FUN = function(x){
paste0(sample(x = LETTERS, size = 60, replace = T), collapse = "")}))

#Score data
score_set = replicate(n = 3, expr = {data.frame(other = rep("other", 4),
score=sample(1:7,4,TRUE))}, simplify = F)

#Plot function
plotgen<-function(score_set,other,score){
p <- ggplot(score_set, aes(factor(other), score))
p + geom_violin(fill = "#99CCFF") + coord_flip() + scale_x_discrete(name=NULL) +
scale_y_continuous(breaks = round(seq(1, 7, by = 1),1), limits = c(1,7), name=NULL) +
theme(axis.text.y=element_blank(),axis.title.y=element_blank(),axis.ticks.y=elemen t_blank(),
panel.grid.major.y = element_line(colour = "black"),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = "white"),
panel.border = element_rect(colour = "black", fill=NA, size=1)) +
geom_hline(yintercept=sample(1:7,1,TRUE), size = 1.5, colour = "#334466")
}

#Generate plots
print(lapply(seq_along(score_set), FUN = function(x){plotgen(score_set[[x]],other,score)}))

out <- cbind(row.names(items), as.character(items$text), sprintf("![](%s%s-%s.png)",
opts_current$get("fig.path"), opts_current$get("label"), 1:nrow(items)))

#Build table
kable(out, col.names = c("ID", "Text", "Scores"))
```


enter image description here

Answer

lapply returns a list. When you print a list, regardless of it's contents, it also prints the list indices, [[1]], [[2]], [[3]]. If you instead save the list,

plot_list <- lapply(seq_along(score_set), FUN = function(x){plotgen(score_set[[x]],other,score)})

and then print each plot in the list instead of printing the list (and this we can wrap in invisible() so the returned list isn't printed)

invisible(lapply(plot_list, print))

it won't print the indices of the list. Because you will be printing plots, not printing a list which happens to contain plots.


Demonstrating on a simple list:

x = list(1, 2, 3)
print(x)
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2
# 
# [[3]]
# [1] 3

invisible(lapply(x, print))
# [1] 1
# [1] 2
# [1] 3

An alternate solution, not requiring invisible because it doesn't return anything, is just a for loop:

 for (i in seq_along(plot_list)) print(plot_list[[i]])

I'll leave it to you to see which you prefer.