knitr doesn't convert xtable output on R 3.0.2 - r

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'.

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)

knit2pdf formatting incorrectly, producing warnings

I have been using knitr for a while to generate some quite complex PDFs. On one of my machines knit2pdf started to cause me issues, and I cannot figure out why. knit2pdf continues to work on my other machines.
My typical setup is:
test.Rnw
\documentclass{article}
\begin{document}
This is a test
\end{document}
R Command
knit2pdf(input = "latex/test.Rnw", output = 'latex/knit2pdf', clean = TRUE)
however, I receive the following error message:
knit2pdf(input = "latex/test2.Rnw", output = 'latex/knit2pdf', clean = TRUE)
processing file: latex/test2.Rnw
|.................................................................|
100% ordinary text without R code
output file: latex/knit2pdf
[1] "latex/knit2pdf.pdf" Warning message: running command
'"C:\PROGRA~1\MIKTEX~1.9\miktex\bin\x64\texify.exe" --quiet --pdf
"knit2pdf" --max-iterations=20 -I
"C:/PROGRA~1/R/R-33~1.2/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-33~1.2/share/texmf/bibtex/bst"' had status 1
and the contents of knit2pdf.pdf is:
article[]graphicx[]color fgcolorrgb0.345, 0.345, 0.345
[1][rgb]0.686,0.059,0.5691[1][rgb]0.192,0.494,0.81[1][rgb]0.678,0.584,0.6861[1][rgb]0,0,01[1][rgb]0.345,0.345,0.3451[1][rgb]0.1framed
kframetotalleftmargin# setminipage #end#of#kframe shadecolorrgb.97,
.97, .97 messagecolorrgb0, 0, 0 warningcolorrgb1, 0, 1 errorcolorrgb1,
0, 0 knitrout alltt upquote.styupquote document This is a test
I have managed to get the output I require (using the example from How to create multiple PDFs with different content from a single data frame?), but with significantly more work than just calling knit2pdf.
filename <- "texi2pdf"
f_tex <- paste0("latex/", filename, ".tex")
f_pdf <- paste0("latex/", filename, ".pdf")
knit("latex/test.Rnw", output = f_tex)
tools::texi2pdf(file = f_tex, clean = TRUE, quiet = FALSE)
file.rename(from = paste0(filename, ".pdf"), to = f_pdf)
And in this case the PDF output (texi2pdf.pdf) is simply, and correctly,
This is a test
I am running R 3.3.2 and all packages are up to date.
The solution as outlined by Yihui Xie on Github is to append the output file with '.tex'
i.e.
knit2pdf(input = "latex/test.Rnw", output = 'latex/knit2pdf.tex', clean = TRUE)
I was running knitr v1.11 which did not require this, but later versions do.

Error handling within Sexpr

How do I permit errors within \Sexpr?
I have a knitr document. A small part of this document refers to a file that cannot be shared. So whenever \Sexpr{a} is called on for some object a that depends on that file being read, it returns an error. I'd like instead for \Sexpr to print that it encountered an error.
For example,
\documentclass{article}
\usepackage{xcolor} % for red
\begin{document}
<<>>=
x <- 1
#
The value of $x$ is \Sexpr{x}
<<>>=
a <- scan("secret_file.txt")
#
The value of $a$ is \Sexpr{a}.
\end{document}
will not compile (when secret_file.txt isn't present). I'd like the output to look something like:
I thought that altering the inline hook would work, but putting the following chunk made no difference.
<<Sexpr-setup>>=
library(knitr)
knit_hooks$set(inline = function(x){
out <- tryCatch(
{
if (is.numeric(x))
x = round(x, getOption("digits"))
paste(as.character(x), collapse = ", ")
},
error = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr error!}}")
invisible(NULL)
},
warning = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
invisible(NULL)
}
)
return(out)
})
#
It is not essential to have a custom error message, only that errors are clear from the output and do not prevent compilation. I appreciate that I could do a find replace into something like \Sexpr{XX( and define a function upfront XX() that does the same tryCatch maneouvre, but I thought knitr could do this.
Calling knitr::knit on the above and applying the traceback shows that:
11: eval(expr, envir, enclos)
10: eval(parse_only(code[i]), envir = envir)
9: withVisible(eval(parse_only(code[i]), envir = envir))
8: inline_exec(block)
7: in_dir(opts_knit$get("root.dir") %n% input_dir(), inline_exec(block))
6: call_inline(x)
5: process_group.inline(group)
4: process_group(group)
3: withCallingHandlers(if (tangle) process_tangle(group) else process_group(group),
error = function(e) {
setwd(wd)
cat(res, sep = "\n", file = output %n% "")
message("Quitting from lines ", paste(current_lines(i),
collapse = "-"), " (", knit_concord$get("infile"),
") ")
})
2: process_file(text, output)
1: knitr::knit("knitr-prevent-errors.Rnw", quiet = TRUE)
From following the functions, it appears that the error is low down at
eval(parse_only(code[i]), envir = envir)
Where code[i] is a. Am I right in thinking that the only way to resolve this is to change the line starting v = with a tryCatch?
With the option include=FALSE in the setup chunk,the following worked for me with output as below. If it does not work for you I will delete the post
\documentclass{article}
\usepackage{xcolor} % for red
<<setup, include=FALSE>>=
knit_hooks$set(inline = function(x) {
out <- tryCatch(
{
if (is.numeric(x))
x = round(x, getOption("digits"))
paste(as.character(x), collapse = ", ")
},
error = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr error!}}")
invisible(NULL)
},
warning = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
invisible(NULL)
}
)
return(out)
})
#
\begin{document}
<<>>=
x <- 1
#
The value of $x$ is \Sexpr{x}
<<>>=
a <- scan("secret_file.txt")
#
The value of $a$ is \Sexpr{a}.
\end{document}
Knitr Output:
>knitr::knit("test.Rnw")
processing file: test.Rnw
|......... | 14%
ordinary text without R code
|................... | 29%
label: setup (with options)
List of 2
$ include: logi FALSE
$ indent : chr " "
|............................ | 43%
ordinary text without R code
|..................................... | 57%
label: unnamed-chunk-1 (with options)
List of 1
$ indent: chr " "
|.............................................. | 71%
inline R code fragments
|........................................................ | 86%
label: unnamed-chunk-2 (with options)
List of 1
$ indent: chr " "
|.................................................................| 100%
inline R code fragments
output file: test.tex
[1] "test.tex"
Tex Output:
>texi2pdf("test.tex")
>
I am using MikTex 2.9,knitr 1.9, R 3.0.2 on Windows , can you please attach your log files then we can compare the differences if any

rmarkdown error with ggplot and png

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!

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

Resources