Difference generating image between .Rmd and .R - r

The code below is a full .Rmd file that successfully generates a .pdf file with a hovmoller plot of surface temperature. (I apologize for pasting the whole file, but it is short and I'm not sure what might be causing the problem - though I believe it is in the last section of the code.) The data file is here: https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT.4.6.0.0.median.nc
When I run the .Rmd file, it seems to work flawlessly. It generates a .pdf file that is 230kb that contains a (rather informative) hovmoller plot. If, however, I put the code into a .R file (or run it line by line from the .Rmd file), it still generates a .pdf file, but it is empty and generates an error message if I try to open it.
Can anybody tell me why this happens?
---
title: "Hovmoller plot - HadCRUT4 through November 2018"
author: "jbtg"
date: "January 1, 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r warning=FALSE,message=FALSE}
library(maptools)
library(ncdf4)
library(raster)
library(rasterVis)
library(RColorBrewer)
library(zoo)
library(sf)
library(rgdal)
```
```{r}
#HADCRUT4 combined air temp/SST anomaly as of November 1, 2018
#read a 3D netCDF dataset
hadcrut4_path <- "C:/Users/jtene/Dropbox/!!!netcdf/Rmarkdown/"
hadcrut4_name <- "HadCRUT.4.6.0.0.median.nov18.nc"
hadcrut4_file <- paste0(hadcrut4_path,hadcrut4_name)
hadcrut4 <- brick(hadcrut4_file) #opens anomaly netCDF file (calls nc_open)
hadcrut4 #gives a summary of the file contents
print(c(filename(hadcrut4), hasValues(hadcrut4), inMemory(hadcrut4)))
```
Set up and produce the Hovmöller plot:
```{r}
#setup
idx <- seq(as.Date('1850-01-01'), as.Date('2018-11-01'), 'month')
idx <- as.yearmon(idx)
tmpplt <- setZ(hadcrut4, idx)
names(tmpplt) <- as.character(idx)
#plot
trellis.device('pdf', file = 'hov_hadcrut4.pdf')
hovmoller(tmpplt, dirXY=y,
at = do.breaks(c(-3.5,3.5),14),
contour = F, interpolate = F,
par.settings=RdBuTheme(region=rev(brewer.pal(9,'RdBu'))),
main="HadCRUT4 Anomalies 1850-2018 (1961-1990 base period)")
dev.off
```

Related

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.

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)

How to generate report in pdf format using R

I am trying to find out the R code which will give me the output of the statistical analysis(i.e. Regression, DOE, Gage RR) in pdf or html format by using R ( Not by using R-studio). I want to generate report of my statistical analysis. Is there any R code which we can run in to the R to make pdf or html file ??. I know it for graphs only,
pdf("output.pdf")
x=rnorm(100,40,3)
y=rnorm(100,100,5)
fit=lm(y~x)
summary(fit)
plot(y)
dev.off()
This code gives me graph in pdf but I want all the summary of fit (ANOVA) and all information that R generates. Thanks
Yes, RMarkdown/knitr is the way to go.
See here for the documentation for creating a pdf document.
Your Rmd file might look something like the following:
---
title: "Report"
author: "XXX"
date: "January 7, 2017"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Output
```{r}
x <- rnorm(100, 40, 3)
x
y <- rnorm(100, 100, 5)
y
fit <- lm(y ~ x)
summary(fit)
```
## Plot
```{r plot, echo=FALSE}
plot(y)
```
For an html document, simply change to output: html_document.
Render the pdf or html document with rmarkdown::render('filepath/yourfile.Rmd')

R Markdown: plots within a loop going out of margin when typesetting to PDF

When typesetting an R Markdown document to PDF, if a function draws multiple plots, those plots often appear side-by-side, with only the first plot fully within the margins of the page.
Minimal R Markdown example:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
for (i in 1:3) {
plots()
}
```
Here is a screenshot of page 2 of the generated PDF
which shows the problem. I have searched online, but haven't yet found a solution to this problem.
Thank you.
The plot hook solution proposed by user2554330 is simple and works well. So this code draws all the plots within the margins of the resulting PDF:
---
title: "Example re plotting problem"
author: "Daniel E. Weeks"
date: "May 3, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Multiple plots within a loop
```{r}
plots <- function() {
plot(rnorm(100))
hist(rnorm(100))
}
```
## Call plotting function
```{r}
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
for (i in 1:3) {
plots()
}
```
The problem is that the generated .tex file has no spaces between the \includegraphics{} calls. LaTeX gives warnings about overfull hboxes, because the graphics aren't big enough to sit alone on a line, and are too big when it puts two on each line.
You can tell LaTeX (TeX really) to output the bad lines without putting two figures on each line by adding
\pretolerance=10000
in the text before the code chunk. You'll probably want to set it back to its default value
\pretolerance=100
after the code chunk, or LaTeX won't try hyphenation afterwards, and text can look really ugly.
Another way to fix this would be to force each figure to be in its own paragraph. You can do this by adding this code
my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)
into a code chunk before you do your plotting. This puts a blank line
before and after each figure.

Using layout with knitr

I want to make a single figure in R with two plots in a markdown file with knitr. Normally, this is easy to do with layout(t(1:2)) or par(mfrow=c(1,2)). Can I do this with knitr, or will it always make two separate figures?
Here is a minimum working example which creates a file called ./junk.Rmd and ./junk.md in your working directory along with two files ./figure/junkislands1.png (which only includes the first plot) and ./figure/junkislands2.png (which includes both plots that I want).
require(knitr)
temp <- "```{r junkislands, fig.width=8, fig.height=5}
layout(t(1:2))
pie(islands)
barplot(islands)
```"
cat(temp, file="junk.Rmd")
knit("junk.Rmd", "junk.md")
The problem isn't so much that it creates two .png files, but rather that the markdown file junk.md includes both of them.
When I make that markdown into html, it includes both .png files when I only want the one with both figures plotted.
Here is the file junk.md that is generated from knitr:
```r
par(mfrow = c(1, 2))
pie(islands)
```
![plot of chunk junkislands](figure/junkislands1.png)
```r
barplot(islands)
```
![plot of chunk junkislands](figure/junkislands2.png)
Have a look at http://yihui.name/knitr/options and specifically fig.keep. I think you want fig.keep = 'last'
require(knitr)
temp <- "```{r junkislands, fig.width=8, fig.height=5, fig.keep = 'last'}
layout(t(1:2))
pie(islands)
barplot(islands)
```"
cat(temp, file="junk.Rmd")
knit("junk.Rmd", "junk.md")
gives
```r
layout(t(1:2))
pie(islands)
barplot(islands)
```
![plot of chunk junkislands](figure/junkislands.png)

Resources