compiling latex file generated by RStudio - latex

I am trying to edit the latex file generated by RStudio but it seems the file generated by RStudio does not compile out of the box.
Here is the template rmarkdown (edited a little as I want to show code in my slides)
---
title: "Untitled"
author: "SN248"
date: "April 17, 2016"
output:
beamer_presentation:
keep_tex: true
theme: "CambridgeUS"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
Some code
```{r eval=FALSE, echo=TRUE}
install.packages("mypackage")
library(mypackage)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=TRUE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Note, that I added keep_tex: true to get the intermediate tex file, the generated tex file is pasted below:
\begin{frame}[fragile]{R Markdown}
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see \url{http://rmarkdown.rstudio.com}.
Some code
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"mypackage"}\NormalTok{)}
\KeywordTok{library}\NormalTok{(mypackage)}
\end{Highlighting}
\end{Shaded}
\end{frame}
\begin{frame}[fragile]{Including Plots}
You can also embed plots, for example:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{plot}\NormalTok{(pressure)}
\end{Highlighting}
\end{Shaded}
\includegraphics{Untitled_files/figure-beamer/pressure-1.pdf}
Note that the \texttt{echo\ =\ FALSE} parameter was added to the code
chunk to prevent printing of the R code that generated the plot.
\end{frame}
I noticed that the generated tex file does not compile out of the box. So, I added the necessary bits (i.e., package listings for code highlighting) so that it compiles
\documentclass[hyperref={pdfpagelabels=false}]{beamer}
\usepackage{lmodern}
\usepackage{listings}
\usetheme{CambridgeUS}
\begin{document}
...
\end{document}
I am still not able to compile this tex file as the bit begin{Shaded} does not compile, I get the following error:
LaTeX Error: Environment Shaded undefined
My question is, how to generate tex file from RStudio which compiles out of the box. If not, which packages should I use to compile the tex code (especially to show code with highlighting) shown below
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"mypackage"}\NormalTok{)}
\KeywordTok{library}\NormalTok{(mypackage)}
\end{Highlighting}
\end{Shaded}
Just to give some context, I am trying to compile the tex file so that I can add sections and subsections in the tex code, I am not sure how to do that in the rmarkdown file.
Thank you very much for your help.
SN248

I can see that you are using RMarkdown and want to generate a stand alone .tex file that can be compiled without knitr.
I do the same thing with SWeave. As SWeave is a latex document with R code, you can easily compile it once SWeave is run and figures are created.
For Example, I have created this document in RStudio and compile it in Rstudio.
\documentclass{article}
\title{Best title ever}
\author{XTriMa, PhD}
\begin{document}
\maketitle
\tableofcontents
\section{Method} \label{intro}
Let me make two vectors with random numbers and plot them.
<<>>=
x<-runif(100)
y <- x^(sin(x))
plot(x, y)
#
\end{document}
My folder looks like this
figure test.log test.Rnw test.tex
test-concordance.tex test.pdf test.synctex.gz test.toc
Now if you run
$pdflatex test.tex
It works as you intended. However command "latex" will not work as it can not work with pdf graphics in figures.
Advantage: I can work with R and latex very efficiently and get rid of intermediate software/clients like RStudio and Sweav.

Related

How to convert Rmarkdown file to working latex file

I have written a manuscript I would like to submit to a journal in Rmarkdown. The journal accepts word and latex files, so I am looking for a way to generate a working .tex file out of my .Rmd file.
I have read some posts that allude to this being possible (e.g., How to generate LaTeX file without preamble in R markdown?) and this is getting me some of the way, but I am still having problems.
For example, using the method mentioned in the post above, I can convert a test .Rmd into something with a .tex filetype. This is the test Rmarkdown (just the usual template for new files):
---
title: "Test document"
author: "Me"
date: "23 7 2020"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
This compiles fine to PDF as it should. Then, in the console I run:
knitr::knit("test.Rmd")
to get a markdown file test.md in my working directory, and then I can apparently convert this .md file to .tex with
rmarkdown::pandoc_convert("test.md", to = "latex", output = "test.tex")
This produces a .tex file that, when I double click on it, pops up a PDF view of the file that looks fine. Taking a look at the file though, it is incomplete or at least unfamiliar to me:
\hypertarget{r-markdown}{%
\subsection{R Markdown}\label{r-markdown}}
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see \url{http://rmarkdown.rstudio.com}.
When you click the \textbf{Knit} button a document will be generated
that includes both content as well as the output of any embedded R code
chunks within the document. You can embed an R code chunk like this:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{summary}\NormalTok{(cars)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
\end{verbatim}
\hypertarget{including-plots}{%
\subsection{Including Plots}\label{including-plots}}
You can also embed plots, for example:
\begin{figure}
\centering
\includegraphics{figure/pressure-1.png}
\caption{plot of chunk pressure}
\end{figure}
Note that the \texttt{echo\ =\ FALSE} parameter was added to the code
chunk to prevent printing of the R code that generated the plot.
As far as I can tell, it is missing the preamble, \begin{document}, \end{document}, and I have no idea what is going on with hypertarget bit of the section headers. Unsurprisingly, it does not "re-compile" when I hit run in MiKTeX. The verbatim bits for the code chunks look to be what I'm after, though.
So, is there a way to generate a .tex file that compiles out of an .Rmd file? Or will I have to manually write the preamble and all that? If the answer to my problem is "read up pandoc", then fair enough, I will have to bite the bullet and finally have a look at it. But I find it hard to imagine that there is no good (easy) way to prepare submittable manuscripts in Rmarkdown.
Pandoc generates LaTeX snippets by default, i.e., not a full document. This can be changed by calling pandoc with the --standalone option:
rmarkdown::pandoc_convert(
"test.md",
to = "latex",
output = "out.tex",
options = "--standalone"
)
You can let R do the work and shorten your commands to
render("test.Rmd", output_format = "latex_document")
A project of interest might be rticles.

Pandoc fails to render valid LaTeX macro definitions from markdown (and R markdown)

In R, I have character objects that contain LaTeX macro definitions. The
challenge is to use these objects in R Markdown documents, so that the
macro definitions are rendered correctly when the .Rmd files are converted to
LaTeX (and then to PDF). It is a challenge because Pandoc (v2.9.1 and 2.9.2)
fails to render some macro-generating code correctly, even when that
code is valid LaTeX.
Here is a minimal example. First, consider this Rmd file:
---
title: "Rendering LaTeX Macros from R Objects"
output:
pdf_document:
keep_md: true
keep_tex: true
---
```{r}
withoutBraces <- "\\newcommand\\withoutBraces{This is a sentence.}"
withBraces <- "\\newcommand{withBraces}{This is a sentence.}"
```
```{r, results = "asis"}
writeLines(withoutBraces)
writeLines(withBraces)
```
Knitting this .Rmd file from RStudio produces a .tex file that includes the
following output:
\newcommand\withoutBraces{This is a sentence.}
but
\textbackslash newcommand\{withBraces\}\{This is a sentence.\}
In other words, the \withoutBraces command is rendered correctly in the .tex
document, but the \withBraces command is not. Inspection
reveals that the rmarkdown::render() part of the knitting process is fine, in
the sense that it produces an unproblematic .md file. The problem lies with
pandoc: when it converts the .md file to a .tex file, the \withBraces
command doesn't render correctly.
If I were writing .md files instead of .Rmd files, I could use "generic raw
attributes" in my code chunks to get the \withoutBraces macro definition to
render correctly, as in this example from
#mb21. But I don't see a way to
do that when working with R Markdown files. Is there anything that I can do
to get the \withoutBraces definition to render correctly when I am knitting
an .Rmd file to LaTeX and PDF?
The problem lay with a LaTeX formatting error on my part, not in any problem with pandoc. I had written
withBraces <- "\\newcommand{withBraces}{This is a sentence.}"
when I should have written
withBraces <- "\\newcommand{\\withBraces}{This is a sentence.}"
When I use the second string instead of the first, there is no problem with the conversion to LaTeX.

Using bib2gls with rmarkdown fails to render glossary

I'd like to use the bib2gls latex package in my rmarkdown document to insert a list of acronyms from a .bib file when I knit to a pdf document.
Doesn't work:
Using a .bib file to store my acronyms. Example:
abbreviations.bib file:
#abbreviation{ecoli,
short={E.~coli},
long={Escherichia coli}
}
#abbreviation{raustralis ,
short ={R.~ australis},
long={Rickettsia australis}
}
preamble.tex
% fixes problem with glossaries causing mathspec
% to return an error asking for amsmath to be loaded first
\makeatletter
\let\RequirePackage\original#RequirePackage
\let\usepackage\RequirePackage
\makeatother
% using bib2gls
\usepackage[record,abbreviations,style=index]{glossaries-extra}
\setabbreviationstyle{long-short}
\GlsXtrLoadResources[src={abbreviations},selection={all}]
rmarkdown file:
---
output:
pdf_document:
latex_engine: xelatex
includes:
in_header: preamble.tex
title: "mwe"
---
## R Markdown
This is the first instance \gls{ecoli}, \gls{raustralis}. This is the second instance: \gls{ecoli}, \gls{raustralis}.
\printunsrtglossary[title={Abbreviations},type=abbreviations]
The output when I knit the rmarkdown documents looks like:
What works:
Removing \GlsXtrLoadResources[src={abbreviations},selection={all}] and adding my entries into the preamble.
% using bib2gls
\usepackage[abbreviations,style=index]{glossaries-extra}
\setabbreviationstyle{long-short}
\newabbreviation{ecoli}{E.~coli}{Escherichia coli}
\newabbreviation{raustralis}{R.~australis}{Rickettsia australis}
I'd like to use the separate .bib file in the first approach if possible. Unless there is a better approach to do this in R. Session info is below:
R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
The Problem is that bib2gls requires an additional program to be run, which extracts the glossary entries from the bib file, but rmarkdown does not know about that. In general, if you want to do something more complicated on the LaTeX side, there is a good chance that latexmk already knows how to do that. I am not sure if this is here the case, c.f. https://tex.stackexchange.com/questions/400325/latexmkrc-for-bib2gls. However, you can give it a try using
```{r echo=FALSE}
Sys.setenv(RSTUDIO_PDFLATEX = "latexmk")
```

how to include pdfpages in rmarkdown for beamer output

I am creating pdf slides using rmarkdown and beamer. When using latex instead of rmarkdown, I can include arbitrary pages from pdf files into my slides with
\usepackage{pdfpages}
...
\includepdf[pages={1-10}]{another_file.pdf}
Is it possible to achieve this with rmarkdown? Note that when just issuing the \includepdf command, intended to be located between slides, pandoc wraps it between \begin{frame} and \end{frame}.
Not a perfect solution but it works (adapted from https://tex.stackexchange.com/questions/11458/error-when-inserting-a-pdf-page-into-a-beamer-presentation?newreg=10fd6a4a46c642118eb4ec905cf87303): use \includegraphics instead of includepdf. This works inside of frames but you have to manyally create a frame for each page you want to insert as it only allows to insert a single page at time.
---
title: "Foo"
output:
beamer_presentation:
---
# Stolen image
---
\includegraphics[page=1,width=\paperwidth]{lecture-1-terminal.pdf}
# My own work
## My slide 1
Great stuff!
In rmarkdown you can use pdfpages like this:
---
output:
beamer_presentation:
keep_tex: true
header-includes:
- \usepackage{pdfpages}
- \setbeamercolor{background canvas}{bg=}
- \makeatletter\beamer#ignorenonframefalse\makeatother
---
test
``` {=latex}
\end{frame}
\includepdf[pages=1-10]{example-image-duck}
\begin{frame}
```
test
(the line \setbeamercolor{background canvas}{bg=} is necessary for beamer versions < 3.64, a patch has been added in 9e3bb9)
As you mentioned, you can inlcude raw TeX in Pandoc Markdown. For me the following works:
$ pandoc -t beamer
foo
\includepdf[pages={1-10}]{another_file.pdf}
bar
^D
which results in:
\begin{frame}
foo
\includepdf[pages={1-10}]{another_file.pdf}
bar
\end{frame}
Maybe you need to update your pandoc version? (I'm currenlty using 2.0 from pandoc nightlies)

Remove unwanted latex code from final document.

I made a file in rmarkdown to submit to a journal, but when I went to actually upload the file, they want raw latex. Okay, part of my YAML is.
output:
pdf_document:
keep_tex: true
header-includes:
- \usepackage{color}
- \usepackage{lineno}
- \linenumbers
The preview of the document looks great, except it starts out like this (just text not, in code format:
[]article lmodern amssymb,amsmath ifxetex,ifluatex fixltx2e =0 [T1]fontenc
[utf8]inputenc fontspec Ligatures=TeX,Scale=MatchLowercase upquote microtype
[protrusion]basicmath [margin=1in]geometry hyperref graphicx,grffile parskip
titling
color lineno
followed by everything I want. Where do I look to get rid of this?

Resources