1

Sometimes I had to make more chunks in R markup to "fake" an output in R markup. As an example, since I found out printing a wordcloud2 in R markdown is basically not possible by calling the usual wordcloud2 function, I had to print it out on my pdf but letting it seem like the basic function did it.

```{r}
freq <- data.frame(names(freq),freq, row.names 
                 = 1:length(freq))
library(wordcloud2)
```
```{r eval=FALSE}
wordcloud2(freq,color="random-light", backgroundColor = "grey")
```
```{r echo=FALSE, message=FALSE}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq,color="random-light", backgroundColor = "grey")
saveWidget(hw,"1.html",selfcontained = F)
webshot::webshot("1.html","1.png",vwidth = 700, vheight = 500, delay =10)
```

This is what I have done, in simple words I made a non visible chunk print the wordcloud instead of the "graphic" one.

This is the result:

enter image description here

I know that probably nobody would notice, but having the chunks visually separated is not very beautiful.

Is there a way to unify those two?

Thank you in advance.

A. S. K.
  • 2,504
  • 13
  • 22

1 Answers1

0

How about making the whole first chunk "fake", and then copying the parts that need to run into the second chunk?

```{r eval = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r echo = F, message = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```

Alternatively, if you want to avoid copying too much code, you could label the chunks and use the approach in this answer to print them together:

```{r load_data, echo = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
```

```{r make_wordcloud, eval = F, echo = F}
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r display_code, ref.label = c("load_data", "make_wordcloud"), eval = F}
```

```{r make_wordcloud_image, echo = F, message = F}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```
A. S. K.
  • 2,504
  • 13
  • 22