Dynamic plots and tables inside Rmarkdown - r

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.

Related

Assign figure caption to html widget (vtree package) in R markdown output

I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT.
But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help!
In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.
my iris set example RMD file:
YAML
---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---
code chunk 1: load libraries and data
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
select(Species) %>%
cbind(sapply(levels(.$Species), `==`, .$Species))
code chunk 2: Figure 1
{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")
code chunk 3: Figure 2
{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
xlab="Sepal Length ", ylab="Sepal Width ", pch=19)
There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ยด{r eval = FALSE}, otherwise you will get an error during rendering:
```{r eval=FALSE, echo = FALSE}
myimage <- vtree(iris, "Species")
saveMyimage <- grVizToPNG(myimage, width=800)
```
Here you use the Magickpackage:
```{r magick, echo= FALSE}
MyimagePNG <- image_read("myimage.png")
image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
```

How do I get Bookdown to properly knit a PDF with multiple code chunks?

I am transitioning to Bookdown from Markdown. Although it seems as though this should be straightforward I am getting an unexpected knit failure once I have added the 3rd (usually) code chunk in a chapter (not index.rmd) file. I have tried using code from the example code by Allaire and Xie with the same result. The problem does not occur if all the markdown code is in one file i.e. no chapters. Here is the sample code from the index and 1st chapter files. Sorry about the formatting; I'm not sure how to format markdown code in stackoverflow so the 3 back tics consistently show.
---
classoption: openany # Removes blank pages (Arrgh!!)
site: "bookdown::bookdown_site"
output:
bookdown::tufte_book2:
latex_engine: xelatex
---
```{r setup, include=FALSE}
library(ggplot2)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion("tufte"))
```
And this is the first chapter code:
# Figures
## Margin Figures
Images and graphics play an integral role in Tufte's work. To place figures in the margin you can use the **knitr** chunk option `fig.margin = TRUE`. For example:
```{r fig-margin, fig.margin = TRUE, fig.cap = "MPG vs horsepower, colored by transmission.", fig.width=3.5, fig.height=3.5, cache=TRUE, message=FALSE}
library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
geom_point() + geom_smooth() +
theme(legend.position = 'bottom')
```
In fact, you can include anything in the margin using the **knitr** engine named `marginfigure`. Unlike R code chunks ```` ```{r} ````, you write a chunk starting with ```` ```{marginfigure} ```` instead, then put the content in the chunk. See an example on the right about the first fundamental theorem of calculus.
```{marginfigure}
We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$:
$$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$
```
It fails here
knitr::kable(
mtcars[1:6, 1:6], caption = 'A subset of mtcars.'
)
Deleting the code after "It fails here" makes it knit properly for me.
Dropbox link with scripts, log, and pdf's.

Remove progress bar from knitr output

I'm analyzing some data and would like to do a Simpsons paradox on R. I've installed the Simpsons package and loaded the library. Here is an example based on the package documentation:
---
output: html_document
---
```{r}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
This is returning a plot with 3 clusters (exactly what I need). However, when I Knit the Rmd file to HTML, I'm getting a lot of equals signs (======) with a percentage next to it like a loading grid which I would like to remove from my final output.
You can suppress any output messages in R by setting the knitr chunk option. If we wish to hide all code output other than plots, we can use the following solution:
---
output: html_document
---
```{r echo=FALSE, results='hide', fig.keep='all', message = FALSE}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
I would note that this package seems to print out a lot more content that most packages, and therefore the combination of options are quite long.
An easier method would probably be to move the plot to a separate chunk and have all the analysis run before it. The include argument can be used to suppress all outputs, but this includes plots, hence why we must use two chunks:
```{r, include = FALSE}
# your code to build model
```
```{r}
plot(example)
```
Check out the full list of knitr chunk options here

How to widen output window for text?

I am want to print the output of a linear mixed model and the texts wraps.
Is there option that gets around this problem?
I have tried option(width=1000) and tidy=TRUE,tidy.opts=list(width.cutoff=600) to no avail.
EDIT:
Here is a minimum reproducible example.
---
title: "Untitled"
author: "NickHayden"
date: "5/8/2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(lmerTest)
library(lme4)
library(tidyverse)
```
## 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 cars}
df <- sample_n(diamonds, size = 100)
df <- df %>% mutate(randoms = rep(c("A","B", "C"), length.out = 100))
mod <- lmer(price ~ factor(color) * factor(clarity) * factor(cut) + (1|randoms), data = df)
print(summary(mod))
```
Here the text should wrap around the window and lines may wrap under as well.
An anternative is to export the output to a text file. The following link shows how to achieve this.
Export R output to a file
Example:
test <- c("asb", "asb", "asb", "abc")
out <- capture.output(summary(test))
cat("My title", out, file="example_output.txt", sep="\n", append=TRUE)

Problems with simultaneous use Sankey and d3tree htmlwidgets on R Notebook?

I use R notebook for data analysis report.
I want to render Sankey and d3tree htmlwidgets on R notebook simultaneously.
I put snakey and then d3tree example code in r chunk, output is well printed on rstudio.
When I entered preview button, sankey output well appeared on html.
But, d3tree output doesn't render on html.
I tryed that put d3tree and then sankey. the result is that two of d3tree and sankey dosen't render on html.
what is the problem??
Can i solve these?
the example code like below
---
title: "test"
output: html_notebook
---
```{r, echo=FALSE}
library(networkD3)
library(treemap)
library(d3treeR)
```
```{r, echo=FALSE}
net_cycles <- list(
links = data.frame(
source = c(0,0,0,1,1,5),
target = c(1,2,3,4,5,0),
value = 10
),
nodes = data.frame(
name = letters[1:6]
)
)
```
```{r, echo=FALSE}
data(business)
business$employees.growth <- business$employees - business$employees.prev
tree <- treemap(business,
index=c("NACE1", "NACE2"),
vSize="employees",
vColor="employees.growth",
type="value",
palette="-RdGy",
range=c(-30000,30000))
```
```{r}
sankeyNetwork(
net_cycles$links,
net_cycles$nodes,
Value = "value"
)
d3tree2(
# Brewer's Red-White-Grey palette reversed with predefined range
tree
,rootname = "World"
)
```

Resources