invalid connection when using ggplot2 in rmarkdown - r

even a simple histogram such as I have included in the rmarkdown code below:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
mtcars <- mtcars
p <- ggplot(data=mtcars, aes(x=mpg))
p + geom_histogram()
```
returns the histogram in the rmarkdown window, but in the console returns:
Error in isIncomplete(con) : invalid connection
Error in isIncomplete(con) : invalid connection
Error in isIncomplete(con) : invalid connection
this error is returned three times. I am not sure what could be closing the connections, or perhaps it's something different all together. Any thoughts?

Related

Print a plot I have saved in the environment anywhere in Rmarkdown

I create an Rmarkdown document where I would like to create a plot at the start of the document, and then print it at the end of the document.
I thought the best way to achieve this would be to save the plot in the environment and then recall it later, I save this as follows:
plot(1:5, 1:5) ; plot1 <- recordPlot() # I create a plot and save it as plot1
This plot is saved under "Data" in the environment.
If I enter plot1 into the console, my plot is reproduced, but when I try to display it directly in Rmarkdown as follows I get the following error:
plot(plot1)
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' is a list, but does not have components 'x' and 'y'
How I can take the plot that I saved into Data and print it anywhere I would like in my Rmarkdown document?
p.s. I know it's tempting to say to repeat the plot again later in the document, but the parameters that build the plot are subsequently altered for another part of my analysis.
Re-producible example:
x = 1
plot_later <- function() {
plot(x)
}
plot_later()
x = -10
plot_later()
X starts at 1 then changes to -10 on the Y axis, I want it to stay at the initial value of 1.
Solution based on https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html :
---
title: plot now, render later
output: html_document
---
We put some plot expression here to evaluate it later:
```{r, deja-vu, eval=FALSE}
x = 1
plot(x)
```
Here we change `x` - but only within the corresponding chunk's scope:
```{r}
x = 10
```
... moving on
Here, we evaluate and plot the expression defined earlier; x is taken from that chunk's scope, so it still evaluates to `1`:
```{r, deja-vu, eval=TRUE}
```
One option could be saving the plot as grob object using as.grob function from ggplotify and then print it elsewhere.
---
title: "Saving A Plot"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
library(ggplotify)
library(grid)
show_captured_plot <- function(grb) {
grid::grid.newpage()
grid::grid.draw(grb)
}
```
```{r}
x <- 1
p <- as.grob(~plot(x))
```
Now we can plot the figure here.
```{r}
x <- 10
show_captured_plot(p)
```
here, check out this link: https://bookdown.org/yihui/rmarkdown-cookbook/fig-chunk.html
It has a lot of instructions on how to get started with rmarkdown.
Specifically answering your question:
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
After another paragraph, we introduce the plot:
![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)
Basically you have to save your graph as a variable and then call on it using the knitr::fig_chunk() function.

How to make Rmarkdown carry over sections of code?

I have a piece of RMarkdown code that runs fine in one block.
```{r}
library(tidyverse)
data("PlantGrowth")
set.seed(1234)
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```
However, if I try to break it into pieces of code, which I need to do in order to add explanations, I get the following error in the RMarkdown console.
```{r eval=TRUE}
library(tidyverse)
data("PlantGrowth")
set.seed(1234)
```
Comment the code here
```{r eval=TRUE}
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```
Say more stuff...
Error in PlantGrowth %>% sample_n_by(group, size = 1) : could not find function "%>%" Calls: <Anonymous> ...withVisible -> eval_with_user_handlers -> eval -> eval Execution Halted.
Is there a way to make markdown carry over the libraries and variables loaded in previous code blocks up to the end of the document?
Make sure you insatlled tidyverse and rstatix in your env.
```{r eval=TRUE}
library(tidyverse)
library(rstatix)
data("PlantGrowth")
set.seed(1234)
```
Comment the code here
```{r eval=TRUE}
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```

R markdown doesn't find object

I am using R markdown to knitter my codes into a word document
I am pretty new to R as well as to R markdown
I have the following code :
{r, eval=TRUE, fig.height=7, fig.width=5, message=FALSE, warning=FALSE}
lifeExpectancy <- rename(lifeExpectancy, Incomegroup= WORLDBANKINCOMEGROUP)
plife <- ggplot(lifeExpectancy, aes(x= LifeExpectancy))
plife1 <- plife + geom_histogram(fill="white", aes(color= Incomegroup))
plife1 <- plife1 +facet_grid(SEX~Incomegroup) + xlab("average life
expectancy")
plife1
this is the warning message it returns :
Quitting from lines 32-38 (Termpaper_Franziska.Rmd)
error in rename_(.data, .dots = lazyeval::lazy_dots(...)) :
Object 'lifeExpectancy' not found
calls : <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval
> rename -> rename_
stopped`
What I already did :
I set the working directory correctly for R markdown as well as for my original script
I used
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir =
"C:/Users/Maxi/Desktop/PrettyPlots2016/Termpaper")
to set the working directory but that didn't help either.
Last but not least I also set
eval=FALSE
but then I didn't get my plot of course, which didn't help me either.
If anyone has a solution for my dilemma I would be very happy to hear it !
Thank you a lot !

Cannot create PDF from R Markdown without template file lines

I am trying to create a long document in R Studio using R Markdown to PDF, and I am getting the following error when I push the "Knit PDF" button:
! Undefined control sequence.
l.124 \begin{center}\includegraphics
pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted
I am able to properly create the PDF if I make a new R Markdown document and I paste the code in from the original, provided I keep the following code at the end of the new document. When I erase this code, I get the above error.
```{r, echo=FALSE}
plot(cars)
```
I have no need or desire for the cars plot to be in my document. I am able to Knit this document into HTML without the undesired code, but not to PDF. Can anyone advise why this error may be happening? (This is my first post to this forum, so if you need more specific information, please advise).
I am running Windows 7 32 bit, R Studio version 0.98.1103, MiKTeX version 2.9.
Edit/Update: Here is my code, including the cars graph which I do not want.
---
title: "Untitled"
date: "Saturday, April 25, 2015"
output: pdf_document
---
```{r echo=FALSE, warning=FALSE, include=FALSE}
require(qcc)
require(data.table)
require(ggplot2)
require(sm)
require(knitr)
require(xtable)
attach(airquality)
airquality$indicator <- ifelse(airquality$Month < 8,'Classic','New')
```
```{r echo=FALSE, warning=FALSE, results='hide', fig.align='center'}
par(mfrow=c(2,1), oma=c(1,1,1,1), cex=.5, mex=.5, ps=8, mgp=c(3,1,0))
airquality <- airquality[complete.cases(airquality),]
# Plot variable on an SPC chart of type xbar.one
imrchart2 <- qcc(airquality$Ozone[airquality$indicator=="Classic"], "xbar.one", std.dev="SD", add.stats=TRUE, ylab="Ozone", title="Xbar.One Chart for Ozone", xlab="", data.name="Classic", restore.par=FALSE, newdata=airquality$Ozone[airquality$indicator=="New"], newdata.name="New", ylim=range(airquality$Ozone))
# Plot a CUSUM chart
cusum(airquality$Ozone[airquality$indicator=="Classic"], sizes=1, add.stats=TRUE, ylab="Ozone", title="CUSUM Chart for Ozone", xlab="", restore.par=FALSE, newdata=airquality$Ozone[airquality$indicator=="New"], data.name="Classic", newdata.name="New")
```
```{r, echo=FALSE}
plot(cars)
```

Rstudio does not make plots with knit Word

I seem to have discovered an odd behaviour with the knit Word command in RStudio
This works:
```{r qplot, fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
````
this does not work
```{r q plot, fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
```
returning this message:
pandoc.exe: Could not find image `./test_files/figure-docx/q%20plot.png', skipping...
The issue seems to be with the name of the chunk (i.e. qplot vs. q plot). When there is a space in the chunk name the plot does not render.
It only seems to affect the rendering of Word documents. Rendering html works fine.
I'm using RStudio 0.98.1028 and R3.1.1 on windows 7.
Has anyone else encountered this behaviour?
update
a space after the chunk name also seems to elicit the same behaviour:
this does not work
```{r q_plot , fig.width = 6, fig.height=6, message=FALSE}
library(ggplot2)
summary(cars)
qplot(speed, dist, data = cars) + geom_smooth()
```
Posting the solution in case someone runs across this in future.
From Ben Bolker in the comments Avoid spaces and periods . in chunk labels and directory names as stated in the knitr documentation http://yihui.name/knitr/options.
This error only seems to affect making plots using knitWord. Code chunks with labels that contain spaces and that don't have plotting commands render normally. knitHTML also seems to work fine regardless of if chunk labels have a space or not.
# Let's make a plot
```{r ugly plot}
plot(btc_prices)
```
should apparently be
# Let's make a plot
```{r ugly_plot}
plot(btc_prices)
```
So no spaces... otherwise you'll waste hours googling and crying.

Resources