create PDF with preamble from rmarkdown::render - r

I am trying to create a PDF from R. I am successful from within RStudio (choosing "Knit to PDF"), but I get an error invoking from R (either with ctl-enter in Rstudio or with Rscript --vanilla invoke_from_R.R from the command line). My actual need is to create from the command line.
For example:
invoke_from_R.Rmd
---
title: "Lumber Jacks"
author: "Washington Irving"
date: "2022-09-19"
output:
pdf_document:
keep_tex: true
keep_md: true
dev: pdf
includes:
in_header: invoke_from_R_preamble.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Where are we?
Dove siamo?
invoke_from_R_preamble.tex
\newcommand\T{\rule{0pt}{2.6ex}} % Top strut
\newcommand\B{\rule[-1.2ex]{0pt}{0pt}} % Bottom strut
invoke_from_R.R
rmarkdown::render(
input = "invoke_from_R.Rmd"
, output_file = "invoke_from_R.pdf"
, output_format = rmarkdown::pdf_document(
rmarkdown::includes(in_header = "invoke_from_R_preamble.tex"),
toc = TRUE
, toc_depth = 2
, number_sections = FALSE
, keep_md = TRUE
, keep_tex = TRUE
, fig_width = 6.5
, fig_height = 4.5
, fig_crop = FALSE
)
)
The error that I get is:
$ Rscript --vanilla invoke_from_R.R
Error in !implicit_figures : invalid argument type
Calls: <Anonymous> ... <Anonymous> -> output_format -> pandoc_options -> from_rmarkdown
Execution halted
I have not yet found a workaround.
When I comment out this line:
rmarkdown::includes(in_header = "invoke_from_R_preamble.tex"),
I don't get the error, but I need to use the preamble because some of my LaTeX macros get processed even when I use the setting that is supposed to prevent this.
I am using (on Linux):
R version 4.2.1 (2022-06-23)
rmarkdown 2.14
Suggestions?
Thank you.

Related

Quarto and knitr to external file

I have a directory Project/Package/R with three files: script.R, knitr.Rmd and quarto.qmd.
This is knitr.Rmd:
---
title: "Essai"
output: pdf_document
---
```{r, include=FALSE}
library(here)
knitr::opts_knit$set(root.dir = here())
source(here("Package","R","script.R"), local = knitr::knit_global())
```
This is quarto.qmd:
---
title: "Essai"
format:
pdf:
toc: true
toc-depth: 2
---
```{r, include=FALSE}
library(here)
knitr::opts_knit$set(root.dir = here())
source(here("Package","R","script.R"), local = knitr::knit_global())
```
All is OK with knitr compilation, but quarto can't find the script R:
Quitting from lines 10-14 (stack.qmd)
Erreur dans readChar(con, 5L, useBytes = TRUE) :
impossible d'ouvrir la connexion
Appels : .main ... source -> withVisible -> eval -> eval -> load -> readChar
Exécution arrêtée
What is wrong? Thank you in advance.

How to use pass variables in rmarkdown pdf?

I'm trying to pass variables to rmarkdown report as params but i'm not able to render it in the report
the below one is my code the my_value param is dataframe having only single row
---
title
output:
pdf_document: default
output:
pdf_document:
keep_tex: true
classoption: svgnames
header-includes:
- \usepackage{amsfonts,amssymb,amsmath}
params:
my_class:"smile"
my_value: data$percent
--
`r params$my_value` is the total percentage of customers
`r params$my_class` is product which has been doing better
The YAML header you're using isn't valid.
title tag should finish by : and have a value : title: "test"
output should only be used once
finish header with ---
Try:
---
title: "test"
output:
pdf_document:
keep_tex: true
header-includes:
- \usepackage{amsfonts,amssymb,amsmath}
classoption: svgnames
params:
my_class: "smile"
my_value: NA
---
Regarding parameters, you can't directly use data$percent as parameter value in YAML header.
Knitting is done in a new environment, data$percent doesn't exist in it.
In YAML, you could use following settings:
params:
my_class:"smile"
my_value: NA
In calling script:
# data definition
data <- ...
params <- list(
my_class = "more smiles",
my_value = data$percent
)
rmarkdown::render("MyDocument.Rmd", params = params)
For more information : https://bookdown.org/yihui/rmarkdown/params-knit.html

! 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".

Rstudio pandoc issue

This example will knit on my laptop but not my desktop. Both are using the same RStudio and R versions. I have tried uninstalling R and RStudio, changing R and RStudio versions, changing 32/64 bit R, trying to install a variety of pandoc versions, setting the path to pandoc manually with Sys.setenv()... I am sort of at a loss here.
Both machines have the following:
> rmarkdown::pandoc_version()
[1] ‘1.19.2.1’
> version
_
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 4.3
year 2017
month 11
day 30
svn rev 73796
language R
version.string R version 3.4.3 (2017-11-30)
nickname Kite-Eating Tree
Here is a minimum non/working example. Again, it works on the laptop but not the desktop.
---
title: "Pandoc testing sandbox"
output:
html_document:
df_print: paged
number_sections: yes
toc: yes
toc_float:
collapsed: no
smooth_scroll: no
---
Here is a chunk of code to test:
```{r, results = "asis", echo = FALSE, message = FALSE}
tex2markdown <- function(texstring) {
writeLines(text = texstring,
con = myfile <- tempfile(fileext = ".tex"))
texfile <- knitr::pandoc(input = myfile, format = "html")
cat(readLines(texfile), sep = "\n")
unlink(c(myfile, texfile))
}
textable <- "
\\begin{table}[]
\\centering
\\begin{tabular}{l | c | c}
& without replacement & with replacement \\\\ \\hline
order matters & permutation: $\\frac{n!}{(n-k)!}$ & $n^k$ \\\\ \\hline
order does not matter & combination: ${n\\choose k}=\\frac{n!}{k!(n-k)!}$ & (\\textit{special case}) \\hline
\\end{tabular}
\\end{table}
"
tex2markdown(textable)
```
The error text on the desktop machine is:
Line 17 Error in knitr::pandoc(input = myfile, format = "html") :
Please install pandoc first: http://pandoc.org
Calls: <Anonymous> ... withVisible -> eval -> eval ->
tex2markdown -> <Anonymous> Execution halted
Any help with this would be greatly appreciated!
===
Edit: I did a bit more testing and ran:
rmarkdown::render("pandoctest.Rmd", "html_document")
And there was an option to "Rerun with Debug", so I did that, and the error is happening in "Function pandoc (namespace:knitr)" The line of code where the break happens in what I suppose is the pandoc function in the knitr package is:
...
if (Sys.which("pandoc") == "")
stop("Please install pandoc first: http://pandoc.org")
...
So it seems like pandoc is checking to see if it is installed itself? Or somehoe this is a pandoc function in the knitr package that is calling an actual pandoc program from somewhere else? SO it seems I need to get knitr to somehow see that I have pandoc installed.

Execute multiline R expression from shell (with indentation)

I'm trying to achieve what you might naively write as:
R -e "
rmarkdown::render(
'MyDocument.Rmd',
params = list(
year = 2017
),
output_file = 'ExampleRnotebook.html'
)
"
So that I can make nicely formatted submission scripts to run on a cluster.
I've tried some variants on the below, I'm wondering if there might be an alternative approach to do this with the R -f flag?
read -r -d '' EXP << EOF
rmarkdown::render(
'MyDocument.Rmd',
params = list(
year = 2017
),
output_file = 'ExampleRnotebook.html'
)
EOF
R -e "$EXP"
but I get a series of errors that look like this:
ARGUMENT 'params~+~=~+~list(' __ignored__
for the different lines of the expression, followed by:
> rmarkdown::render(
+
+ Error: unexpected end of input
To reproduce:
MyDocument.Rmd =
---
title: "R Notebook"
output: html_notebook
params:
year: 0000
---
```{r}
params$year
```
This works fine:
read -r -d '' EXP <<- EOF
rmarkdown::render('MyDocument.Rmd', params = list(year = 2017 ), output_file = 'ExampleRnotebook.html')
EOF
R -e "$EXP"
but gets hard to read with longer param lists
This works for me (R version 3.5.0):
R --no-save <<code
for(i in 1:3) {
i +
2
}
print(i)
runif(5,
1,10)
code
Note: line-breaks and paddings are intentional.

Resources