knitr does not compile pdf - r

I'm new to coding and I`m trying to use knitr to print a PDF. I have installed R 3.5.3 and RStudio installed correctly as simple codes usually run.
I have both installed in the same folder as Miktex 2.9.7
As I create a new markdown file with a PDF output, incoded in UTF-8, I get the standard model text.
I've tried different encodings and reinstalled miktex several times.
When I run a code I used at my uni lab, it runs, but if I alter even 1 character on a string and save it, it wont compile the pdf anymore.
This is what I've been trying to compile:
---
title: "Lista 1"
date: "April 6, 2019"
output: pdf_document
---
```{r instalar pacotes necessarios}
# Carregando os pacotes necessários
if (!require("pacman")) install.packages("pacman")
pacman::p_load("tinytex", "tidyverse")
```
Questão 1
Use os conhecimentos adquiridos em sala de aula (e fora dela!) para realizar >as seguintes operações sobre o
banco de dados mpg:
```{r variaveis q1a}
posicao <- 100
item.a <- mpg[posicao, c("manufacturer","model")]
```
a) A partir do código acima podemos verificar que o veículo de posição `r posicao` banco de daados é um `r item.a`
```{r}
media.milhas.cidade <- mean(mpg$cty)
```
b) A partir do código acima, pode-se verificar que a média de milhas por galão na cidade é `r media.milhas.cidade`
I should just get the pdf but Rstudio prints this:
================================
processing file: lista1mkd.Rmd
|......... | 14%
ordinary text without R code
|................... | 29%
label: instalar pacotes necessarios
|............................ | 43%
ordinary text without R code
|..................................... | 57%
label: variaveis q1a
|.............................................. | 71%
inline R code fragments
# A tibble: 1 x 2
manufacturer model
<chr> <chr>
1 honda civic
|........................................................ | 86%
label: unnamed-chunk-1
|.................................................................| 100%
inline R code fragments
"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS lista1mkd.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output lista1mkd.tex --template "C:\Users\CESARA~1\DOCUME~1\R\WIN-LI~1\3.5\RMARKD~1\rmd\latex\DEFAUL~3.TEX" --highlight-style tango --latex-engine pdflatex --variable graphics=yes --variable "geometry:margin=1in" --variable "compact-title:yes"
output file: lista1mkd.knit.md
Error: Failed to compile lista1mkd.tex. See https://yihui.name/tinytex/r/#debugging for debugging tips.
In addition: Warning message:
In readLines(logfile) : incomplete final line found on 'lista1mkd.log'
Execution halted

Related

Adding additional lua-filter into YAML

I'm trying to add an additional lua-filter into the YAML:
---
title: "TITLE"
subtitle: "SUBTITLE"
date: "07/04/2022"
output:
pdf_document:
pandoc_args:
- --lua-filter=/Users/user/.local/share/pandoc/filters/wordcount.lua
latex_engine: pdflatex
includes:
in_header: style.sty
#keep_tex: true
bookdown::pdf_book:
citation_package: biblatex
bibliography: literature.bib
csl: my.csl
lang: de
fontsize: 12pt
---
ok, now when I try to knit the document I'm getting this erorr:
/usr/local/bin/pandoc +RTS -K512m -RTS mother.knit.md --to latex --from markdown+autolink_bare_uris+tex_math_single_backslash --output mother.tex --lua-filter /Users/user/Library/R/x86_64/4.1/library/rmarkdown/rmarkdown/lua/pagebreak.lua --lua-filter /Users/user/Library/R/x86_64/4.1/library/rmarkdown/rmarkdown/lua/latex-div.lua --self-contained --highlight-style tango --pdf-engine pdflatex --include-in-header style.sty --variable graphics --lua-filter=/Users/user/.local/share/pandoc/filters/wordcount.lua --variable 'geometry:margin=1in' --citeproc
655 words in body
4171 characters in body
4791 characters in body (including spaces)
Error in readLines(con, warn = FALSE) : cannot open the connection
In addition: Warning message:
In readLines(con, warn = FALSE) :
cannot open file 'mother.tex': No such file or directory
What is wrong with the mother.tex? Why it's not been created?
Hope someone can help. Thanks already.
Ok, I struggled a little bit to find the right position for the wordcout: process argument.
But a solution for those one who try to achive a workaround could be the following:
edit the following file from https://github.com/pandoc/lua-filters/blob/04e2d663dcb374d2c79ad1a42a30714843cb4e40/wordcount/wordcount.lua
notice the comment-out lines in line 39-42 and 43-45
-- counts words in a document
words = 0
characters = 0
characters_and_spaces = 0
process_anyway = false
wordcount = {
Str = function(el)
-- we don't count a word if it's entirely punctuation:
if el.text:match("%P") then
words = words + 1
end
characters = characters + utf8.len(el.text)
characters_and_spaces = characters_and_spaces + utf8.len(el.text)
end,
Space = function(el)
characters_and_spaces = characters_and_spaces + 1
end,
Code = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
text_nospace = el.text:gsub("%s", "")
characters = characters + utf8.len(text_nospace)
characters_and_spaces = characters_and_spaces + utf8.len(el.text)
end,
CodeBlock = function(el)
_,n = el.text:gsub("%S+","")
words = words + n
text_nospace = el.text:gsub("%s", "")
characters = characters + utf8.len(text_nospace)
characters_and_spaces = characters_and_spaces + utf8.len(el.text)
end
}
-- check if the `wordcount` variable is set to `process-anyway`
--function Meta(meta)
-- if meta.wordcount and (meta.wordcount=="process-anyway"
-- or meta.wordcount=="process" or meta.wordcount=="convert") then
process_anyway = true
-- end
--end
function Pandoc(el)
-- skip metadata, just count body:
pandoc.walk_block(pandoc.Div(el.blocks), wordcount)
print(words .. " words in body")
print(characters .. " characters in body")
print(characters_and_spaces .. " characters in body (including spaces)")
if not process_anyway then
os.exit(0)
end
end
The problem is that the filter stops the conversion process, so no output is created.
I'm assuming you are using the wordcount filter from https://github.com/pandoc/lua-filters. That filter will abort the document conversion unless the metadata field wordcount is set to the string process or convert.
So you can add --metadata=wordcount=process this to pandoc_args setting:
pandoc_args:
- --lua-filter=/Users/user/.local/share/pandoc/filters/wordcount.lua
- --metadata=wordcount=process
or modify the filter to always process the document regardless of whether the metadata field is set or not.

Rmarkdown stop generating after a paragraph

So my problem is that after a specific paragraph Rmarkdown doesn't generating the rest of the code and I don't know why. Note that if I delete that paragraph the program will render untill the next text paragraph and then do the same thing.
Here is a minimal markdown example with the problematic paragraph. The code block and text after the code block do not show up in the PDF.
---
title: "Proiect Regresie"
author: "Andrei Alexandru; grupa 322"
output: pdf_document
---
# Estimarea parametrilor
Considerăm modelul de regresie liniară simplă $y=\beta_{0}+\beta_{1}x +\varepsilon$ (unde x venitul provenit din vanzarile in America de Nord iar
y venitul provenit din vanzarile la nivel mondial, $\varepsilon$ este repartizat normal de medie 0 și varianță sigma p\u atrat. Estimatorii parametrilor $\beta_{0}$ \c si $\beta_{1}$ ob\c tinu\c ti prin metoda celor mai mici pătrate sunt calcula\c ti \^in R.
```{r}
mtcars
```
Some more text.
Apparently, the special characters (\c, etc.) are causing this problem. You need to specify the language using babel. Since it is a LaTeX package, you need to put it in header-includes in YAML.
Here are two examples of the changes you need to do:
\c si needs to be rewritten \c{s}i
ob\c tinu\c ti needs to be rewritten ob\c{t}inu\c{t}i
However, I can't figure out why using \^i or \^{i} does not work.
Full example:
---
title: "Proiect Regresie"
author: "Andrei Alexandru; grupa 322"
output: pdf_document
header-includes:
- \usepackage[romanian]{babel}
---
# Estimarea parametrilor
Considerăm modelul de regresie liniară simplă $y=\beta_{0}+\beta_{1}x +\varepsilon$ (unde x venitul provenit din vanzarile in America de Nord iar
y venitul provenit din vanzarile la nivel mondial, $\varepsilon$ este repartizat normal de medie 0 și varianță sigma p\u{a}trat. Estimatorii parametrilor $\beta_{0}$ \c{s}i $\beta_{1}$ ob\c{t}inu\c{t}i prin metoda celor mai mici pătrate sunt calcula\c{t}i \^{i}n R.
```{r}
mtcars
```
Some more text.

! Illegal unit of measure (pt inserted) PDF Knit Error

I'm trying to knit a report as a PDF in RStudio. The code I have so far works fine (I've been testing it chunk by chunk) until it gets to the below chunk:
## HCT-CI
```{r}
summaryTable(y=wdata$HCTCI.score, table.title="HCT-CI Raw Score", y.labels="Number of Readmissions")
summaryTable(y=wdata$HCTCI.score, table.title="Readmissions", freq.tab=T, y.name="HCT-CI Raw Score")
summaryTable(y=wdata$HCTCI.3cat, table.title="HCT-CI Score (3 Groups)", caption_heading="Note:", caption="1: Score=0; 2: Score=1-2; 3: Score=3+", freq.tab=T, y.labels=c("0", "1-2", "3+"))
```
\pagebreak
My goal is to generate the output successfully as a PDF.
It's the same functions and format I've used in all the other chunks. When I run the chunk by itself, it also works. I've looked up the issue on google and other stackoverflow posts, but am having a hard time applying their solutions as they all use HTML or a different language.
My full report looks something like this (with some chunks taken out for the sake of brevity):
DOCUMENT BEGINS
---
title:
- \vspace{2in}Analysis for Study$\colon$ Readmissions
subtitle:
- \vspace{.2in}\emph{`r format(Sys.time(), '%d %B, %Y')`}
author:
- \emph{PI$\colon$ Name}
- \emph{College}
- \vspace{.5in}\emph{Author}
- \emph{Position}
- \emph{email}
date:
- \vspace{4in}
header-includes:
- \usepackage{fancyhdr}
- \usepackage{titling}
- \usepackage{caption}
- \fancyhead[L]{\includegraphics[width=2cm]{pic.png}}
- \fancyhead[R]{\includegraphics[width=4cm]{pic.png}}
- \fancyfoot[C]{Department}
- \fancypagestyle{plain}{\pagestyle{fancy}}
geometry: left=.5in,right=.5in,top=1in,bottom=1in
mainfont: Times New Roman
output:
pdf_document:
keep_tex: true
highlight: tango
toc: true
toc_depth: 4
number_sections: true
fig_caption: true
df_print: kable
fontsize: 12pt
---
\captionsetup[table]{labelformat=empty}
```{r setup, include=FALSE}
source("Revised Code.R")
knitr::opts_chunk$set(fig.path='Figs/', fig.align='center', fig.pos="H", echo=FALSE, warning=FALSE, message=FALSE, results = 'asis', fig.width = 6.5, fig.height = 4.5, dev = 'pdf')
\pagebreak
Summary of ___ within 100 days
summaryTable(wdata, table.title="Within 100 Days", y.labels="Number of Readmissions")
summaryTable(wdata, table.title="Within 100 Days", y.labels="Number of Readmissions", freq.tab=T)
summaryTable(wdata, table.title="Within 100 Days", freq.tab=T, y.name="Readmission", y.labels=c("No Readmission", "Any Readmission"))
\pagebreak
Association Between Readmissions and Donor Type
summaryTable(y=wdata$donor, table.title="Donor Type", freq.tab=T, y.name="Donor Type")
summaryTable(y=wdata$donor.3cat, table.title="Association Between Readmissions and Donor Type (3 Groups)", freq.tab=T, y.name="Donor Type", y.labels=c("Matched Sibs", "MUD", "Others"))
regTable.logistic(formula=wdata$readm.any~as.factor(wdata$donor.3cat), response = "Readmission", y.name="Donor Type (3 Groups)", y.labels=c("MUD vs Matched Sibs", "Others vs Matched Sibs"))
summaryTable(y=wdata$readm.any, bygroup=as.numeric(wdata$donor.3cat), freq.tab=T, bygroup.name="Donor Type", y.name="Readmissions", bygroup.labels=c("Matched Sibs", "MUD", "Others"), caption_heading="Note:", caption = "0: No Readmission; 1: Any Readmission")
\pagebreak
Association
HCT-CI
summaryTable(y=wdata, table.title="Raw Score", y.labels="Number of Readmissions")
summaryTable(y=wdata, table.title="Readmissions", freq.tab=T, y.name="Raw Score")
summaryTable(y=wdata, table.title="Score (3 Groups)", caption_heading="Note:", caption="1: Score=0; 2: Score=1-2; 3: Score=3+", freq.tab=T, y.labels=c("0", "1-2", "3+"))
\pagebreak
DOCUMENT ENDS
It's only when I attempt to knit it as a PDF do I get the following error:
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
! Illegal unit of measure (pt inserted).
<to be read again>
)
l.1949 \item
\underline{\textit{Note:}}
Error: Failed to compile Revised_Code.tex. See https://yihui.name/tinytex/r/#debugging for debugging tips. See Revised_Code.log for more info.
Execution halted
How do I resolve the issue?
The "Illegal unit of measure (pt inserted)." error may also appear when a numerical value is entered for the chunk option out.height. For example out.height=200 generates this error, it should be replaced by out.height="200px".

How to set cache directory in knitr

I am trying to figure out how to change the cache directory for knitr. I already tested some approaches:
```{r setup, echo = FALSE}
library(knitr)
library(png)
library(grid)
library(tufte)
library(ggplot2)
library(xtable)
opts_chunk$set(cache.path("../.intermediates"))
Gives me:
Error in cache.path("../.intermediates") : não foi possível encontrar a função "cache.path"
```{r setup, echo = FALSE}
library(knitr)
library(png)
library(grid)
library(tufte)
library(ggplot2)
library(xtable)
knitr::cache.path("../.intermediates")
```
Results in:
Erro: 'cache.path' is not an exported object from 'namespace:knitr'
Using the yaml:
link-citations: true
lang: pt-BR
csl: chicago-fullnote-bibliography.csl
links-as-notes: yes
header-includes: |
\renewcommand{\figurename}{Figura}
knit: cache.path("../.intermediates")
Results in:
1: In file.rename(from, to) :
não foi possível renomear o arquivo '/home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/reports/stats_files/figure-latex' para '/home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/.intermediates//home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/reports/stats_files/figure-latex', motivo 'Arquivo ou diretório não encontrado'
2: In file.rename(from, to) :
não foi possível renomear o arquivo '/home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/.intermediates//home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/reports/stats_files/figure-latex' para '/home/luis/Dropbox/Documentos/Psiquiatria/Projetos/LIVRO-stats/reports/stats_files/figure-latex', motivo 'Arquivo ou diretório não encontrado'
What is the proper way of setting the cache directory?
opts_chunk$set(cache.path = " ")

How properly use knit2html?

I'm trying to produce a HTML using that script:
title: "SQL"
date: "`r format(Sys.time(), '%Y-%m-%d')`"
output:
html_document:
keep_md: yes
---
```{r setup, echo = FALSE}
library(knitr)
path <- "drive"
extension <- "sql"
```
This document contains the code from all files with extension ``r extension`` in ``r paste0(getwd(), "/", path)``.
```{r, results = "asis", echo = FALSE}
fileNames <- list.files(path, pattern = sprintf(".*%s$", extension))
fileInfos <- file.info(paste0(path, fileNames))
for (fileName in fileNames) {
filePath <- paste0(path, fileName)
cat(sprintf("## File `%s` \n\n### Meta data \n\n", fileName))
cat(sprintf(
"| size (KB) | mode | modified |\n|---|---|---|\n %s | %s | %s\n\n",
round(fileInfos[filePath, "size"]/1024, 2),
fileInfos[filePath, "mode"],
fileInfos[filePath, "mtime"]))
cat(sprintf("### Content\n\n```\n%s\n```\n\n", paste(readLines(filePath), collapse = "\n")))
Using the same setup & R-scripts and same directories on a Windows machine works well. I suppose there is a problem with encoding.
Sometimes the execution begins with:
During startup - Warning messages:
1: Setting LC_CTYPE failed, using "C"
2: Setting LC_COLLATE failed, using "C"
3: Setting LC_TIME failed, using "C"
4: Setting LC_MESSAGES failed, using "C"
5: Setting LC_MONETARY failed, using "C"
6: Setting LC_PAPER failed, using "C"
7: Setting LC_MEASUREMENT failed, using "C"
and the execution just hangs
Then I have to:
Sys.setenv(LANG="de_DE.UTF-8")
and re-execute. Following output appears:
processing file: all_SQLs.Rmd
|................ | 25%
inline R code fragments
|................................ | 50%
label: setup (with options)
List of 2
$ echo : logi FALSE
$ indent: chr " "
|................................................. | 75%
inline R code fragments
|.................................................................| 100%
label: unnamed-chunk-1 (with options)
List of 2
$ results: chr "asis"
$ echo : logi FALSE
output file:SQL.knit.md
/usr/lib/rstudio-server/bin/pandoc/pandoc +RTS -K512m -RTS SQL.utf8.md --to html --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash- implicit_figures --output all_SQLs.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template /usr/local/lib/R/site-library /rmarkdown/rmd/h/default.html --variable 'theme:bootstrap' --include-in-header /tmp/RtmpBkTBSH/rmarkdown-str50021b4e910.html --mathjax --variable 'mathjax- url:https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX- AMS-MML_HTMLorMML' --no-highlight --variable highlightjs=/usr/local/lib/R/site- library/rmarkdown/rmd/h/highlight
pandoc: Cannot decode byte '\xfc': Data.Text.Internal.Encoding.Fusion.streamUtf8: Invalid UTF-8 stream
Error: pandoc document conversion failed with error 1
I suppose there is a problem with encodings. However I tried all I could by setting the locale in R as well as in Ubuntu to one standard:
locale R
[1] LC_CTYPE=de_DE.UTF-8 LC_NUMERIC=C LC_TIME=de_DE.UTF-8
[4] LC_COLLATE=de_DE.UTF-8 LC_MONETARY=de_DE.UTF-8 LC_MESSAGES=de_DE.UTF-8
[7] LC_PAPER=de_DE.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C
Locale Ubuntu
LANG=de_DE.UTF-8
LANGUAGE=
LC_CTYPE="de_DE.UTF-8"
LC_NUMERIC="de_DE.UTF-8"
LC_TIME="de_DE.UTF-8"
LC_COLLATE="de_DE.UTF-8"
LC_MONETARY="de_DE.UTF-8"
LC_MESSAGES="de_DE.UTF-8"
LC_PAPER="de_DE.UTF-8"
LC_NAME="de_DE.UTF-8"
LC_ADDRESS="de_DE.UTF-8"
LC_TELEPHONE="de_DE.UTF-8"
LC_MEASUREMENT="de_DE.UTF-8"
LC_IDENTIFICATION="de_DE.UTF-8"
LC_ALL=
When using knit2html() instead of the Knit HTMLbutton in Rstudio `I'll get the following:
warning:
1: In readlines (con):
incomplete last line in '/SQL.Rmd'
2: In RegExpr (".. '? [Hh] [1-6] *> (*) </ [Hh] [1-6] *.?>", Html, perl = TRUE):
Input string 1 is incorrect UTF-8
3: In Grepl (i, html, perl = TRUE):
Input string 1 is incorrect UTF-8
4: In Grepl (i, html, perl = TRUE):
Input string 1 is incorrect UTF-8

Resources