I am trying to create an R Markdown file and include a formula. The problem is that when I knit the document the formula appears as I have entered in a latex style.
---
output: github_document
---
$$P(E|L) = \frac{P(L|E) * P(E)}{P(L)} = \frac{0.3 * 0.5}{0.3 * 0.5 + 0.5*1} = 0.23$$
So when I knit it, it looks like:
where as in the code it appears.
What should I do so that when I knit the document, the formula looks like in the second picture?
The problem is coming from your use of the output format github_document. The github output format cannot directly support the maths mode. As stated by the rmarkdown package author in this issue:
I'd say that if you really care about LaTeX math in Markdown, you should render to HTML output instead of waiting indefinitely for Github to support MathJax in Markdown, which I doubt will ever happen.
Implementing his advice, we can change the output format to html_document:
---
output: html_document
---
$$
P(E|L) = \frac{P(L|E) * P(E)}{P(L)} = \frac{0.3 * 0.5}{0.3 * 0.5 + 0.5*1} = 0.23
$$
Related
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.
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.
I am trying to produce a PDF document with R markdown which includes some equations and r code. I am trying to align sub-items in an un-ordered list which appear after the equations.
Below is the code. I want the words Prediction and Inference to start as new sub items.
---
title: "Test"
author: "Author"
date: "21 April 2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
* Main Point
+ **Prediction** - Some text here
$$
\hat{Y}=\hat{f(X)}+\epsilon ............... (2.2)
$$
$$
E( Y - \hat{Y} )^2
= E[f(X) + \epsilon - \hat{f(X)}]^2
=[f(X) - \hat{f(X)}]^2+Var(\epsilon) ......... (2.3)
$$
+ **Inference** - Some text here
No matter what spacing I try, nothing seems to be working. Currently, after the "Main Point", I have given two tabs before the "+" before "Prediction". This works absolutely fine and produces the sub item of the "Main Point". However, after the two equations when I try the same formatting that I did for the first sub-item, it does not work at all and produces the alignment as shown in the picture.
Markdown has a few rules to make sublists work. Most importantly in your case, sub-items only work if there is a parent item to it. As Stackoverflow uses the same syntax, we can show the examples inline. For example:
1. Item
2. Item
* Mixed
* Mixed
Item
Item
Mixed
Mixed
In your case, you have put some none list items between the sub-items, as follows:
1. Item
2. Item
* Mixed
Some Text
* Mixed
Item
Item
Mixed
Some Text
* Mixed
As you can see, the list has been broken and is not recognised as an item.
Workaround
If you are only using PDF output, you are able to use LaTeX commands to achieve custom styling. In your case, you can use the hspace command to add a separation:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
* Main Point
\hspace{1cm} + **Prediction** - Some text here
$$
\hat{Y}=\hat{f(X)}+\epsilon ............... (2.2)
$$
$$
E( Y - \hat{Y} )^2
= E[f(X) + \epsilon - \hat{f(X)}]^2
=[f(X) - \hat{f(X)}]^2+Var(\epsilon) ......... (2.3)
$$
\hspace{1cm} + **Inference** - Some text here
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.
I have some .rst files and I convert them to .tex file using standard sphinx converter.
In some .rst I have tables with special width like:
.. list-table::
:widths: 50 50
The resulting .tex always contains tables like:
\begin{tabulary}{\textwidth}{|L|L|}
So, the column width is lost.
How can I preserve column width when converting rst to latex?
I used comma separator too,
.. list-table::
:widths: 50 , 50
:header-rows: 1
* - SETTING
- DESCRIPTION
* - Enable
- Enables or disables internal tracing.
* - Verbose
- Enables or disables extended internal tracing.
but it doesn't work.. maybe I used a bad converter? What converter do you recommend?
actually the command
.. tabularcolumns:: |p{4.5cm}|p{8.5cm}|
is needed just before .. list-table::
https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-tabularcolumns
try:
:widths: 50, 50
with a comma separator.
The output also depends on how your table is written in rst.
I assumed that you were using the standard rst table syntax, not making tables from bulleted lists (as is possible). For more help, try http://docutils.sourceforge.net/docs/ref/rst/directives.html#tables
Also, if the 50, 50 is the column width, your latex code should look like this:
\begin{tabulary}{ 1\textwidth}{ | p{0.5} | p{0.5} | }
and:
\begin{tabulary}{total width of table}{| column width| column width|}
The docutils rst2latex writer has some issues with tables: http://docutils.sourceforge.net/docs/dev/todo.html#tables , so maybe your problem is related to that? I think the Sphinx writer is based on rst2latex and might thus have the same issues.
I can confirm that this:
.. list-table::
:widths: 10 40 50
* - Module
- Link
- Description
Works with rst2latex
\setlength{\DUtablewidth}{\linewidth}
\begin{longtable*}[c]{|p{0.104\DUtablewidth}|p{0.375\DUtablewidth}|p{0.465\DUtablewidth}|}
\hline
Module
&
Link
&
Description
\\
\hline
But with sphinx, I get what the OP put. So not an rst2latex issue I would gather.
The "Auto" width stuff the docs talk about is also not very functional for me, links tend to bleed over.
Since I have a huge documentation, I tried to fix the latex generation. Also, I consider Latex notation in rst files a disadvantage, because it's inconsistent and requires editors to partly learn a touchy markup language.
I replaced LaTeXTranslator.depart_table with my own version. I copied the original depart_table and added this code (shortened):
def my_depart_table (self, node):
totalColwidth = 0
givenColwidth = []
hasColwidth = False
for tgroup in node:
for tableColspec in tgroup:
try:
if tableColspec.has_key('colwidth'):
totalColwidth += tableColspec['colwidth']
givenColwidth.append(tableColspec['colwidth'])
hasColwidth = True
except:
print "colspec missing. \n"
# original code
if hasColwidth:
colspec = ""
for thisColwidth in givenColwidth:
colspec += ('>{\RaggedRight}p{%.3f\\linewidth}' % (0.95 * thisColwidth / totalColwidth))
#print "using widths: %.3f %s %s" % ((0.95 * thisColwidth / totalColwidth), thisColwidth, totalColwidth)
self.body.append('{' + colspec + '}\n')
# more original code
LaTeXTranslator.depart_table = my_depart_table
Im neither fluent in Python nor Sphinx, so use at own risk. I hope you get the idea or can even give advice.
If you use Python < 3.0 and want to remove the factor 0.95 completely, remember to either cast one of the integers to float or import division from __ future __.