2

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

Xander
  • 593
  • 1
  • 5
  • 19
  • 1
    Split your code into two chunks, the first with everything but the `kable` and with the `include=FALSE` option, the second with just the `kable`. Or use `purrr::walk`. – alistaire Sep 09 '16 at 00:28

1 Answers1

9

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 whole 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 each plot individually, 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.


Addressing the worry that a for loop would be slower:

p = ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point()
plist = list(p, p)

library(microbenchmark)
microbenchmark(
    forloop = {for (i in seq_along(plist)) print(plist[[i]])},
    lapply = invisible(lapply(plist, print)),
    times = 10L
)

# Unit: milliseconds
#     expr      min       lq     mean   median       uq      max neval cld
#  forloop 260.4532 271.2784 295.8415 276.1587 289.7507 402.1792    10   a
#   lapply 258.8032 269.5915 296.2268 287.9524 294.8860 398.6803    10   a

The difference is a few milliseconds.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Excellent use of a for loop. It is a bit slower, but generates the desired output. Sometimes I get stuck in the (l/s)apply mindset. This is a good reminder. Thank you! – Xander Sep 09 '16 at 00:31
  • 1
    I would be shocked if the for loop was more than a few microseconds slower. `lapply` being faster than a `for` loop is a common misconception. It is, however, often simpler to write. – Gregor Thomas Sep 09 '16 at 01:06
  • Well, I'm surprised. The median difference is as much as 12 milliseconds. – Gregor Thomas Sep 09 '16 at 01:15
  • 1
    Very clever solution. Regarding the performance: On my system there is basically no speed difference, probably your difference is a measurement artifact. After 100 repetitions I got a difference of only 2.4ms. – CL. Sep 09 '16 at 07:05