rmarkdown error with ggplot and png - r

I have tried (in vain) to produce a chart with ggplot in Rmarkdown.
The code is the following:
```{r,echo=FALSE}
#fig.width=12,fig.height=6
panel2$PlotSize<-round(log(panel2$BSFA0200),0)- min(round(log(panel2$BSFA0200),0))+1# set size of dots
panel2$PlotSize[panel2$PlotSize==-Inf]<-NA
panel2$PlotColour<-ifelse(panel2$PlotSize<7,1,panel2$PlotSize)
panel2$PlotSize<-as.factor(panel2$PlotSize)
panel2$PlotColour<-as.factor(panel2$PlotColour)
g1<-ggplot(data=panel2,aes(x=NFR,y=PROF7*100,size=PlotSize,colour=PlotSize))+ geom_point()
g1
```
Out of knits this works fine, however when executed within a Rmd file (either as html or pdf) I always get this error message
processing file: 1Profti_model.Rmd
|.. | 4%
ordinary text without R code
|..... | 8%
label: setup (with options)
List of 1
$ include: logi FALSE
|........ | 12%
ordinary text without R code
|.......... | 15%
label: unnamed-chunk-1 (with options)
List of 3
$ echo : logi FALSE
$ warning: logi FALSE
$ message: logi FALSE
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
Loading required package: zoo
Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
|............ | 19%
inline R code fragments
|............... | 23%
label: unnamed-chunk-2 (with options)
List of 1
$ echo: logi FALSE
|.................. | 27%
ordinary text without R code
|.................... | 31%
label: unnamed-chunk-3 (with options)
List of 1
$ echo: logi FALSE
Quitting from lines 98-109 (1Profti_model.Rmd)
Error in png(..., res = dpi, units = "in") : unable to start png() device
Calls: <Anonymous> ... in_dir -> plot2dev -> do.call -> <Anonymous> -> png
In addition: Warning messages:
1: Removed 55 rows containing missing values (geom_point).
2: In png(..., res = dpi, units = "in") :
unable to open file '1Profti_model_files/figure-html/unnamed-chunk-3-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
Execution halted
I also tried to work around the problem by saving the chart in a png and load it as picture afterwards. Also no results (see Error with loading png in Rmd file)
Thanks for your help
UPDATE:
Following the suggestions from some of you guys I added a different chunk name and I replicated the code from Davit on my data (see updated code).
Unfortunately the error is still there. Interestingly, knitr cannot write a png but can write a csv in the same folder where the code is (I tested it).
Finally, i tested running this very same code onto my C drive and (surprise!) it works. However, this is for me not very efficient as I don't want to be dependent on a specific machine and I need to share this work with others (so network drive is a must). Moreover, all other package/code work fine in the network drive, only this png() seems to be an issue.
Thanks in advance for you help!
---
title: New Document
author: Me
output:
html_document
---
```{r prova,echo=FALSE, results='asis', message = FALSE, error = FALSE, warning= FALSE}
#.libPaths("D:/xxxx/packages")
require(ggplot2)
panel2 <- data.frame(BSFA0200 = rnorm(100),
NFR = rnorm(100),
PROF7 = rnorm(100))
panel2$PlotSize<-round(log(panel2$BSFA0200),0)- min(round(log(panel2$BSFA0200),0))+1# set size of dots
panel2$PlotSize[panel2$PlotSize==-Inf]<-NA
panel2$PlotColour<-ifelse(panel2$PlotSize<7,2,panel2$PlotSize)
write.csv(panel2[1:100,c('BSFA0200',"NFR","PROF7")],file="test.csv")
g1 <- ggplot(data = panel2,
aes(x = NFR,
y = PROF7 * 100,
size = factor(PlotSize),
colour = factor(PlotSize)
))
g1 + geom_point()
```
Error output:
Loading required package: ggplot2
Quitting from lines 9-32 (test.Rmd)
Error in png(..., res = dpi, units = "in") : unable to start png() device
Calls: <Anonymous> ... in_dir -> plot2dev -> do.call -> <Anonymous> -> png
In addition: Warning messages:
1: Removed 35 rows containing missing values (geom_point).
2: In png(..., res = dpi, units = "in") :
unable to open file 'test_files/figure-html/prova-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
Execution halted
My knitr version is 1.11 (it should be the latest) and R version is 3.2.2
> R.Version()
$platform
[1] "i386-w64-mingw32"
$arch
[1] "i386"
$os
[1] "mingw32"
$system
[1] "i386, mingw32"
$status
[1] ""
$major
[1] "3"
$minor
[1] "2.2"
$year
[1] "2015"
$month
[1] "08"
$day
[1] "14"
$`svn rev`
[1] "69053"
$language
[1] "R"
$version.string
[1] "R version 3.2.2 (2015-08-14)"
$nickname
[1] "Fire Safety"

I got this message as well. The trouble with mine was that the file path was too long. I had my R markdown file in too many sub folders and the name of my R markdown file was too long. Once I reduced the length of the file path, the problem was resolved. I hope that works for you.

I had this same issue once. The code below works. You either had bad header or didn't call the packages: it's hard to tell since you did not provide that information. Also, please post example data next time.
Here is the full code that works (at least for me). If it doesn't run on your machine, post your data and full Rmd script and I'll try to help.
---
title: New Document
author: Me
output:
html_document
---
```{r,echo=FALSE, results='asis', message = FALSE, error = FALSE, warning= FALSE}
require(ggplot2)
panel2 <- data.frame(BSFA0200 = rnorm(100),
NFR = rnorm(100),
PROF7 = rnorm(100),
PlotSize = factor(rep(1:10, 10)),
PlotColour = factor(1:100))
g1 <- ggplot(data = panel2,
aes(x = NFR,
y = PROF7 * 100,
size = PlotSize,
colour = PlotSize))
g1 + geom_point()
```

I have also received this error; I solved it by moving the code to generate the offending figure into its own chunk.

I had a similar problem recently. And in my case, the issue was that antivirus software blocked Rscript.exe while it was trying to process files while knitting and PNG file was not created. So sometimes it is useful to temporarily disable antivirus and check if this solves the issue.

I have struggled with the same error. I understood it was something related to the path but couldn't solve it. Looking at the comments here, I tried closing the software and reopening it. It worked quickly. If this helps someone!

Related

Chunk option eval=FALSE ignored when spinning R-script

Spinning the following code (by clicking compile report in Rstudio):
#+ eval = FALSE
This line should not be syntax-checked, but it is.
Returns this error:
Error in parse(text = x, keep.source = TRUE) :
<text>:2:6: unexpected symbol
1: #+ eval = FALSE
2: This line
Knitting the equivalent Rmd-chunk works fine:
```{r, eval = FALSE}
Using Rmd, eval=FALSE disables the syntax-check, and does not error
I was expecting that I could spin a chunk syntactically incorrect code without getting an error (https://bookdown.org/yihui/rmarkdown-cookbook/spin.html). Am I mistaken for expecting this?
Thanks.
This is not possible, but a workaround is to quote the sentence :
# Syntax checked:
2+2
#> [1] 4
# Not syntax checked:
"
2 a
"
#> [1] "\n2 a \n"
(source: Yihui Xie's comment above at 28jun2022)

Why does a piece of R code does not work during Knit in Rmarkdown

When Knitting ans Rmarkdown (R Studio) document containing chunks of R code a chunck returns
line 192 Error in stats::hclust(dd, method=hc.method) :
must have n>= 2 objects to cluster Calls: <Anonymous> ... eval -> ggcorrplot -> .hc_cormat_order -> <Anonymous>
Same piece of code runs fine when run in R (R Studio) and runs from within markdown. This only happens during Knit!
Made no significant changes code in chunk is copy/paste from R-file. Added cache=FALSE and echo=FALSE. Didn't help.
Did put every line in separate chunk. This showed the error not to be at the library (dplyr) line but at the actual ggcorrplot line
library(dplyr)
dfNed_2b <- dfNed_2a %>% dplyr:: select(grep("GDP", names(dfNed_2a)), grep("GDY", names(dfNed_2a)), grep("GNP", names(dfNed_2a)))
dfNed_2b[is.na(dfNed_2b)] <- 0
corrNed_2b <- round(cor(dfNed_2b), 4)
library(ggcorrplot)
ggcorrplot(corrNed_2b, hc.order = TRUE,
type = "lower",
lab = TRUE,
lab_size = 2,
method="circle",
tl.cex=7,
colors = c("orangered1", "white", "darkolivegreen1"),
title="Correlogram GDP, GDY en GNP indicatoren",
ggtheme=theme_minimal)
From the R code I get a great Correlogram. The knit in Rmd returns:
line 192 Error in stats::hclust(dd, method=hc.method) :
must have n>= 2 objects to cluster Calls: <Anonymous> ... eval -> ggcorrplot -> .hc_cormat_order -> <Anonymous>
Error seem to refer back to first line in chunk while actual error is on the ggcorrplot line(s)
==================================================
Error still seems to persist. Changed Rmd to only use external R scripts
Rmd:
### Correlatie plot van de GDP, GDY en GNP indicatoren
{r cache=FALSE}
knitr::read_chunk('6e_corr_dfNed_2b.R')
```{r 6e_corr_dfNed_2b}
```
R:
## ---- 6e_corr_dfNed_2b
library(dplyr)
dfNed_2c <- dfNed_2b %>% dplyr::select(grep("GDP", names(dfNed_2b)),
grep("GDY", names(dfNed_2b)), grep("GNP", names(dfNed_2b)))
dfNed_2c[is.na(dfNed_2c)] <- 0
head(dfNed_2c,2)
library(ggplot2)
library(scales)
library(ggcorrplot)
corrNed_2c <- round(cor(dfNed_2c), 4)
ggcorrplot(corrNed_2c, hc.order = TRUE,
type = "lower",
lab = TRUE,
lab_size = 2,
method="circle",
tl.cex=7,
colors = c("orangered1", "white", "darkolivegreen1"),
title="Correlogram GDP, GDY en GNP indicatoren",
ggtheme=theme_minimal)
Only thing I can think of is that Knitr does like the library(dplyr) being used in aprevious chunk. Thought that was tackled by the cache=FALSE

Resolving an error running Rmarkdown from the command line

I want to run Rmarkdown from the command line that will save an HTML output (I don't care if the command line shows me the plot as it's run or not, as long as the result is saved).
My Rmd script is something like:
---
title: "Report"
output: html_document
---
`r load("C:/Users/durlij/Desktop/Reports/.RData")`
## This is the Report as of `r format(Sys.Date(), format="%B %d %Y")`.
`r library(knitr)`
```{r error = FALSE, echo=FALSE, message=FALSE, warnings=FALSE, results='asis'}
kable(sumTable, format = "markdown")
```
### Visualization of data
`r library(ggplot2)
library(scales)
options(scipen = 999)`
```{r fig.width=8, fig.height=6, echo=FALSE}
ggplot()
```
```{r fig.width=8, fig.height=6, echo=FALSE}
ggplot()
```
In the command line I run
Rscript -e "library(knitr);require(methods);knit(C:/Users/durlij/Desktop/Reports/myFile.Rmd)"
It starts to run, completes the first in-line code chunk, but gets an error on the ggplot.
The error is:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
Calls: knit ... <Anonymous> -> png -> .handleSimpleError -> h -> cat -> file
In addition: Warning messages:
1: package 'scales' was built under R version 3.1.3
2: In png(..., res = dpi, units = "in") :
unable to open file 'figure/unnamed-chunk-2-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
4: In file(file, ifelse(append, "a", "w")) :
cannot open file 'rmdRun.md': Permission denied
The whole command line echo is:
Warning message:
package 'knitr' was built under R version 3.1.3
Loading required package: methods
processing file: C:/Users/durlij/Desktop/Reports/myFile.Rmd
|..... | 8%
inline R code fragments
|.......... | 15%
label: unnamed-chunk-1 (with options)
List of 5
$ error : logi FALSE
$ echo : logi FALSE
$ message : logi FALSE
$ warnings: logi FALSE
$ results : chr "asis"
|............... | 23%
inline R code fragments
|.................... | 31%
label: unnamed-chunk-2 (with options)
List of 3
$ fig.width : num 8
$ fig.height: num 6
$ echo : logi FALSE
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
Calls: knit ... <Anonymous> -> png -> .handleSimpleError -> h -> cat -> file
In addition: Warning messages:
1: package 'scales' was built under R version 3.1.3
2: In png(..., res = dpi, units = "in") :
unable to open file 'figure/unnamed-chunk-2-1.png' for writing
3: In png(..., res = dpi, units = "in") : opening device failed
4: In file(file, ifelse(append, "a", "w")) :
cannot open file 'rmdRun.md': Permission denied
Execution halted

Trying to publish an R notebook and keep getting the same error (Error in contrib.url(repos, "source") trying to use CRAN without setting a mirror

I use OSX Yosemite with XQuartz as was suggested in other questions, and I've been attempting to publish a notebook but get the same error every time. This is what the .R file looks like:
#' ---
#' title: "MLB Payroll Analysis"
#' author: "Steven Quartz Universe"
#' date: "21 March 2015"
#' output: pdf_document
#' ---
#loading the payroll data from the Python document
payroll <- read.table("~/Documents/payroll.txt", header=TRUE, quote="\"")
View(payroll)
summary(payroll)
bank <- payroll$PayrollMillions
wins <- payroll$X2014Wins
#loading the payroll data from the Python document
payroll <- read.table("~/Documents/payroll.txt", header=TRUE, quote="\"")
summary(payroll)
bank <- payroll$PayrollMillions
wins <- payroll$X2014Wins
#displaying the mean and sd of payroll and wins (out of 162, of course)
mean(bank)
sd(bank)
mean(wins)
sd(wins)
#setting a linear regression
reg <- lm(wins ~ bank)
summary(reg)
#the regression is valid to significance < .10 (p-value .05072),
#but the R-squared is only .1296, a weak correlation
#a means of comparing the histogram to a normal distribution
histNorm <- function(x, densCol = "darkblue"){
m <- mean(x)
std <- sqrt(var(x))
h <- max(hist(x,plot=FALSE)$density)
d <- dnorm(x, mean=m, sd=std)
maxY <- max(h,d)
hist(x, prob=TRUE,
xlab="x", ylim=c(0, maxY),
main="(Probability) Histogram with Normal Density")
curve(dnorm(x, mean=m, sd=std),
col=densCol, lwd=2, add=TRUE)
}
#showing the histogram with normal distribution line
histNorm(reg$residuals, "purple")
#QQplots and Shapiro-Wilk test
qqnorm(reg$residuals)
qqline(reg$residuals)
shapiro.test(reg$residuals)
#p-value is .383; this can be considered a normal distribution
plot(reg$fitted.values,reg$residuals)
abline(h = 0)
#variances are wide, but in a channel
install.packages("lmtest")
library(lmtest)
bptest(reg)
#p-value of .849 given; we can assume variances are constant throughout the distribution
hats <- hatvalues(reg)
hatmu <- mean(hats)
hats[hats > 2 * hatmu]
#we get teams 14 and 19 with high leverage; the Dodgers and Yankees with their astronomical payrolls
treg <- rstudent(reg)
n <- length(treg)
p <- reg$coefficients
df <- n - p - 1
alpha <- 0.05
#no bonferroni correction for outliers
crit <- qt(1 - alpha/2,df)
treg[abs(treg) > crit]
#no outliers are found
#with bonferroni correction
crit <- qt(1 - (alpha/2)/n,df)
treg[abs(treg) > crit]
#no outliers are found
#comparison of outlier tests
pvals <- pt(-abs(treg),df)*2
padjb <- p.adjust(pvals, method = "bonferroni")
padjf <- p.adjust(pvals, method = "fdr")
cbind(pvals,padjb,padjf)
When I hit Compile Notebook, this is the output:
|...................... | 33%
ordinary text without R code
|........................................... | 67%
label: unnamed-chunk-1
processing file: payroll.spin.Rmd
Quitting from lines 9-90 (payroll.spin.Rmd)
Error in contrib.url(repos, "source") :
trying to use CRAN without setting a mirror
Calls: <Anonymous> ... withVisible -> eval -> eval -> install.packages -> contrib.url
I've looked through other questions on how to rectify this, but to no avail. I've done the command line fixes, again to no avail. Could someone point me as to what I'm doing wrong? Thanks kindly.
The line
install.packages("lmtest")
is the problem here. As is hinted by the error message
Error in contrib.url(repos, "source") :
trying to use CRAN without setting a mirror
it is expected that you provide a link to a repo for the package. So changing it to (for instance):
install.packages("lmtest", repos = "http://cran.us.r-project.org")
should do the trick. But as MrFlick and Ben Bolkers pointed out in their comments, it should probably be done when the package is not already installed.
I had this same issue with a Knit HTML publish, i modified the very beginning of the file like so:
---
title: "dialectic"
author: "micah smith"
date: "3/4/2017"
output: html_document
---
```{r setup, include=FALSE}
chooseCRANmirror(graphics=FALSE, ind=1)
knitr::opts_chunk$set(echo = TRUE)
the chooseCRANmirror(graphics=FALSE, ind=1) was the line that fixed it
chooseCRANmirror(graphics=FALSE, ind=1)
knitr::opts_chunk$set(echo = TRUE)
Write this at the start of your chunk if you have already installed the package.
If you have already run your install.packages("___") script, then you can try to set that codechunk to eval = FALSE when you try to knit your markdown file?
If you are installing multiple packages via a pkgs variable just do this. It worked for me. I couldn't knitr to pdf until I fixed it.
pkgs <- c("moments", "ggplot2", "dplyr", "tidyr", "tidyverse")
install.packages(pkgs, repos = "http://cran.us.r-project.org")

knitr doesn't convert xtable output on R 3.0.2

I would like to create a tex table using xtable(). Here's my minimal example which worked when I used the same R version on Win 7.
\documentclass[a4paper,12pt,twoside]{article}
\begin{document}
<<load-packages,include=TRUE,echo=TRUE>>=
library(xtable)
#
<<testing-xtable,echo=TRUE,cache=FALSE,include=TRUE>>=
tab <- matrix(1:50,nrow=10)
rownames(tab) <- letters[1:10]
print(
xtable(
x=tab,
caption="A table",
label="tab",
align=rep("c",times=6),
digits=3,
display=rep("f",times=6)
),
sanitize.colnames.function=identity,
include.rownames=FALSE,
table.placement="h"
)
#
\end{document}
Instead of a nice table I get the verbatim code output of xlatex() in the pdf document.
Here's the output of knitr:
> grDevices::pdf.options(useDingbats = FALSE); require(knitr); opts_knit$set(concordance = TRUE); knit('xtable.Rnw', encoding='UTF-8')
Loading required package: knitr
processing file: xtable.Rnw
|............. | 20%
ordinary text without R code
|.......................... | 40%
label: load-packages (with options)
List of 2
$ include: logi TRUE
$ echo : logi TRUE
|....................................... | 60%
ordinary text without R code
|.................................................... | 80%
label: testing-xtable (with options)
List of 3
$ echo : logi TRUE
$ cache : logi FALSE
$ include: logi TRUE
|.................................................................| 100%
ordinary text without R code
output file: xtable.tex
[1] "xtable.tex"
>
>
Running pdflatex on xtable.tex...completed
Created PDF: ~/Dropbox/intern/sandbox(coding)/tex/chapter/chapter/sandbox/xtable/xtable.pdf
Issues: 2 badboxes
The code chunk testing-xtable should be echoed in the final document but it isn't. This is the pdf output. I'm suspicious about the message Ordinary text without R code. Is this normal?
Any help would be greatly appreciated.
Use the chunk option results='asis'.

Resources