RMarkdown: Long text in code chunks with multiple graphics - r

I am preparing a R markdown document to plot some graphics and some short text accompanying each graphic. The graphics are generated in a code chunk within a loop.
Right now, it looks like this:
First, all the text is outputted, then the graphics. I would like this pattern:
text
graphic
text
graphic
text
graphic
Also, I don't know how to apply line breaks in the cat() output. This is needed to make the whole label visible.
Any ideas on these problems?
This is my code:
```{r, echo = FALSE, comment='', fig.width=8, fig.height=3, fig.show='hold', fig.align='center'}
# vars is a data.frame with some variables names
for (i in 1:nrow(vars)){
options(warn=-1)
label <- 'some long text'
cat(label)
capture.output( data <- analysisFunction(name) )
capture.output( plottingFunctionWithGGplot2(data) )
cat('\n\n')
}
```
Thanks.

Related

Inline text in Markdown - adding results from code

I have been told that I can write a results section for a paper on Markdown. So say I want to get the value Robust_t_time_1 which I have derived in my R code section:
```{r fig.width=4, fig.height=4, echo=FALSE, message=FALSE,
warning=FALSE, include = TRUE}
coefs.robust <- data.frame(coef(summary(model_robust)))
t_values.robust1 <- coefs.robust$t.value
Robust_t_time_1 <- t_values.robust1[3]
Robust_t_time_1
```
And I am writing in the text section of Markdown and I want to quote this value. How do I refer to it? I have been trying t = {r} Robust_t_time_1 . This does not work. I know it should be possible.
To evaluate the value you have to use back ticks in the text: "t = `r Robust_t_time_1`"
You can also render it as an inline equation in the text by using dollar signs: "$t = `r Robust_t_time_1`$"

Dynamic plots and tables inside Rmarkdown

I am new to Rmarkdown and shiny and forgive me for some naive questions. I have build a code in two parts first where I do all the processing and second where I call the Rmarkdown to knit it.
The first code example.R is as follows and works fine independently (with only glitch of plots being trimmed from sides):
# Create a label for the knitr code chunk name
## #knitr ExternalCodeChunk020
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
The second part of the code (mrkdwn.Rmd) is where I try to knit and generate Rmarkdown report:
---
title: "Code Chunks"
author: "Author"
date: "November 13, 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::read_chunk("example.R")
```
This first code chunk prints the externally located code,
but it does not execute the code. The next code chunk
executes the externally located code, but it does not print code
itself. Text output is suppressed, and figures are plotted,
but only after all of the code is executed.
```{r DisplayCodeChunk, eval = FALSE, echo = FALSE}
<<ExternalCodeChunk020>>
```
```{r RunCodeChunk, echo = FALSE, eval = TRUE, results = 'hide'}
<<ExternalCodeChunk020>>
```
the output doesn't contain plots. I am not sure what is going wrong, could anyone of you help me in fixing this.
I know that an easy fix is to put both parts of the code together inside the Rmarkdown like this:
---
title: "test3"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Since I need to process large datasets and generate graphs/plots and table I would prefer to keep them separately, so that my Rmarkdown doesn't crash. May be this is wrong and there could be a better approach, please suggest.
Many thanks for your time and help.

I have a for loop of qplots, how can you structure the plots individually using LaTeX code e.g adding captions to the plots

\begin{figure}[h]
\centering
<<echo=FALSE>>=
for(i in 2:38){
print(my_plot_function(i))
}
#
\end{figure}
This is my code, but what is happening is that when I compile my PDF I only get the first two plots that fit on the first page and I do not get the rest of the plots.
I would like to have all of the plots on separate pages.
And how would I go about adding captions to each individual plot in the for loop.
\documentclass{article}
\begin{document}
<<echo = FALSE, fig.cap = c("First, Second, Third"), results = "asis">>=
library(ggplot2)
for (i in 1:3) {
print(qplot(x = 1, y = i))
cat("Arbitrary \\LaTeX code! \\clearpage")
}
#
\end{document}
You can use the chunk option fig.cap to add captions to your plots. Note that this will wrap your figure in a figure environment, turning it into a float.
Use the chunk option results="asis" to be able to print arbitrary text (including LaTeX markup) into your document using cat().

Looping through a list of ggplots and giving each a figure caption using Knitr

I am creating a series of plots using ggplot2. Each of these are programmatically named and I want use the names to give each their own figure caption. I want to pull the names from the list and pass them to fig.cap dynamically.
Is there a way to do this? Here is a MCVE, and you can switch between the list and the individual plots to see the figures disappear or show up:
---
output: pdf_document
---
```{r, include = FALSE}
library(ggplot2)
library(knitr)
opts_chunk$set(echo=FALSE)
```
```{r}
## Plot 1
listOfPlots <- list(
# Plot 1
ggplot(data = diamonds) +
geom_point(aes(carat, price)),
## Plot 2
ggplot(data = diamonds) +
geom_point(aes(carat, depth))
)
names(listOfPlots) <- c("This is caption 1", "This is caption 2")
```
```{r, fig.cap = c("This is caption 1", "This is caption 2"), echo=TRUE}
listOfPlots
# listOfPlots$`This is caption 1`
# listOfPlots$`This is caption 2`
```
Notes:
Yihui and others have said (https://groups.google.com/forum/#!topic/knitr/MJVLiVyGCro), that to have multiple figures in a chunk and give them a figure caption, you need to have echo=TRUE because inline figures and pandoc stuff.
I don't want to show code and the number of figures may be variable so I don't want to hard code things. Interestingly, using a list of ggplots also does not work even if echo=TRUE. I have to individually call each ggplot.
There needs to be spaces between plots in R Markdown if they are to be given their own caption. As stated by Yihui on your link, the trick here is to add some line breaks between the two images.
```{r, fig.cap=c("Caption 1", "Caption 2")}
listOfPlots[[1]]
cat('\n\n')
listOfPlots[[2]]
```
Note, the double square brackets are used to only return the plot itself.
Using a Loop
Assuming you are looking for a more generalizable method which could work for a list of any length, we can automate the creation of the line breaks between the plots using a loop. Note that results="asis" is required in the chunk header:
```{r, fig.cap=c("Caption 1", "Caption 2"), echo=FALSE, results="asis"}
for(plots in listOfPlots){
print(plots)
cat('\n\n')
}
```
As a final tip, you may wish to use the name of the list directly within the caption. The syntax {r, fig.cap = names(listOfPlots)} would be able to achieve this.

allowframebreaks in beamer shading box disappear using knitr

I have the following code
\documentclass{beamer}
\begin{document}
<<setup, include=FALSE>>=
opts_chunk$set(out.lines = 4)
opts_chunk$set(size = 'footnotesize')
options(width=60)
knit_hooks$set(document = function(x) {
gsub('\\\\(begin|end)\\{kframe\\}', '', x)
})
#
After I do this, the R source code and output which is supposing to be displayed in a shaded box now disappear. Any idea on how to get the shaded box back?

Resources