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

早过忘川 提交于 2019-12-02 03:45:33

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!