Python chunk echos in r-markdown, but not r-notebook - rstudio

I like to take notes inside of r-notebooks and have recently been trying to incorporate python code chunks into some of my documents. I have no problems executing python chunks and displaying the output, but I get different behavior depending on whether I'm using an R-notebook or an R-markdown document. While R-markdown will echo the python code and display the output, R-notebook will only display the output. I have tried explicitly stating echo=T in the chunk, bit it does not change the outcome. Any thoughts on how to get the appropriate behavior in R-notebooks?
EDIT: Will also add that this behavior in notebooks only appears to happen when the code chunk has a printed output. A chunk that does not print will echo code correctly.
Below is an example:
R-notebook example
---
title: "R Notebook"
output: html_notebook
---
Example R-notebook
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
print("Hello world")
```
R-markdown example
---
title: "R Notebook"
output: html_document
---
Example R-notebook
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
print("Hello world")
```

Related

In R markdown in RStudio, how can I prevent the source code from running off a pdf page when bash language is used?

I'm writing a technical book using Bookdown and RStudio. My code chunks are mainly using bash. Everything works fine except when I export the book to pdf, then the source code is partially out of the "box" and even the page if this is long enough. I have read a lot of solutions when r language is used, but none of these solutions works when bash language is used.
Here is my code at the beginning of the .Rmd file:
```{r, global_options, include=FALSE}
knitr::opts_chunk$set(message=FALSE, eval=FALSE,
tidy.opts=list(width.cutoff=60), tidy=TRUE)
```
And then when I write the code chunk:
```{bash}
mongodump --uri="mongodb+srv://cluster0.rh6qzzz.mongodb.net/" --db sample_mflix --username my_username
```
The outputs were produced as shown below (see the end of line):
I would like to avoid this, but I have not found the solution.

How do I get amsmath to work in RMarkdown when knitting to PDF?

In RMarkdown, I have a document I want to knit to pdf. The document has equations for which I need automatic numbering. I had been using the $$ 1+1=2 \tag{1} $$ convention to write equations, but now want to switch to the \begin{equation} 1+1=2 \eq:this_eq \end{equation} convention so that I can have automatic numbering and easy cross referencing of the equations. The few online resources I've found make it seem like this should be fairly straightforward to do. For example here or here. However, I have run into no end of heartbreak in attempting to do it.
I am using version 3.4.3 with RStudio, the tinytex distribution, and have installed bookdown (which I am still not sure is really necessary to achieve my goal here). Here is a repex:
---
title: This title
author: "This guy"
date: "This date"
header-includes:
- \usepackage{amsmath}
output:
pdf_document:
toc: yes
toc_depth: '4'
df_print: kable
fig_caption: yes
latex_engine: xelatex
mainfont: Calibri Light
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Introduction
blah blah...
\begin{equation}
S = X \bar{P}
(\#eq:signals)
\end{equation}
## Later on
blah blah \#ref(eq:signals)
When I try to "knit to PDF" I am running into the error
! Package mathspec Error: `amsmath' must be loaded earlier than `mathspec'.
which has been reported as a bug and "fixed" here, but I am unable to understand the fix or to follow its instructions. What I'm asking for is a set of really clear steps that will get me to where I can run the repex above without incident.
Some things I've tried:
The same error occurs when I replace pdf_document with bookdown::pdf_document2. Or when I remove
header-includes:
- \usepackage{amsmath}
and instead put
includes:
in_header: preamble.tex
after the line latex_engine: xelatex, where "preamble.tex" is a notepad file containing the line \usepackage{amsmath}
The comments in this other SO post seem to suggest that it is not even necessary to say anything about amsmath in the YAML options, which confuses me even more. When I remove any mention of amsmath from the YAML options, I get errors saying that the mathjax script is not recognized, for example:
! Package amsmath Error: \bar allowed only in math mode.
When I try your example, the equation is not labelled successfully.
Then I replace the output setting as bookdown::pdf_book. It works.
---
title: This title
author: "This guy"
date: "This date"
output:
bookdown::pdf_book
mainfont: Calibri Light
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Introduction
blah blah...
\begin{equation}
S = X \bar{P}
(\#eq:signals)
\end{equation}
## Later on
blah blah \#ref(eq:signals)
For my problem, the solution came down to me just changing my latex engine from xelatex to lualatex. My document knit correctly and numbered my equations. For some reason, everywhere I looked they say one should use xelatex. Also I had header-includes: - \usepackage{amsmath} in the YAML header.
I was facing this issue. Thanks for the suggestions above. Here is what worked for me in the output and header-includes parts of the preamble:
output:
bookdown::pdf_book:
latex_engine: lualatex
header-includes:
- \usepackage{amsmath}

Conditional evaluation of knitr chunks with Rstudio "Run" button

I am using conditional evaluation using the eval option in the chunk header. If I write eval=FALSE in the header, the chunk is not evaluated when I knit the document, and also not when I use the Run All (Ctrl+Alt+R) from the Rstudio menu.
The problem arises when I try to provide eval with a variable, e.g. the example below:
```{r setup}
ev_cars = TRUE
ev_pressure = FALSE
```
## First chunk
```{r cars, eval=ev_cars}
summary(cars)
```
## Second chunk
```{r pressure, echo=FALSE, eval = ev_pressure}
plot(pressure)
```
In this example, when I run knitr, then the first chunk is evaluated and the second chunk is not (because ev_pressure=FALSE). However, when I try to run using he Run All (Ctrl+Alt+R) from the Rstudio menu, both chunks are evaluated.
Is there a way to overcome this issue?
I am using Rstudio v 1.1
All the best,
Gil
EDIT: {The chunk options are only used when you knit. The Run All command does not knit the document but execute what is inside chunks, without reading chunks arguments.} This is not totally true, indeed, if eval is set to FALSE or TRUE, it is taken into account.
{Thus, a} way to add options like not executing code inside chunks when running Run All would be to do it in the old way with an if inside the chunk.
```{r setup}
ev_cars = TRUE
ev_pressure = FALSE
```
## First chunk
```{r cars}
if (ev_cars) {
summary(cars)
}
```
## Second chunk
```{r pressure, echo=FALSE}
if (ev_pressure) {
plot(pressure)
}
```
The code is then heavier in this way. But if you use Run All, why not directly knit it ?

Rendering rMarkdown File in a Markdown file

If I were to use rmarkdown::render(myFile) within an rMarkdown file. How would I get the first rMarkdown file to display the rendered second rMarkdown file?
At present I've got:
{r other, results="asis"}
myFile <- "SecondFile.Rmd"
rmarkdown::render(myFile)
But this is just outputting the console text generated while the markdown is being knit, whereas obviously I want the HTML result of the knit.
Okay, after some fiddling the best answer I can come up with is this, but I'm more than happy for someone to correct me if there is a more 'proper' way.
```{r setup}
library(htmltools)
```
##Title
```{r generate, include=FALSE}
rmarkdown::render(myFile)
```
```{r print}
includeHTML(myFile)
```

Use custom citation style in markdown using YAML header

I am trying to use a custom citation style in a markdown file, but the citation uses the default (Chicago) style each time I knit. I have tried changing the output format from a JS reveal presentation to an HTML document to a PDF document, but it still does not work. I am using the knitcitations package to cite using the document's DOI, and the bibliography() function to write the bibliography. I have also tried using the apa.csl style found on Zotero, yet the citation is still done in the default styple. The apa.csl file is stored in the same folder as the file that I am trying to use citations in, as is the newbiblio.bib file, in which I have stored the bibliographical information for the item I want to cite.
Below is my markdown code:
---
title: "htmlcitetest"
citation_package: natbib
csl: "apa.csl"
output:
pdf_document:
pandoc_args: ["--natbib"]
biblio-style: unsrt
bibliography: newbiblio.bib
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(bibtex)
library(knitcitations)
options("citation_format" = "pandoc")
library(RefManageR)
cleanbib()
```
## R Markdown
- This is a citation [^1]
[^1]: `r citet("10.1098/rspb.2013.1372")`
```{r, message=FALSE}
bibliography()
```
This link (http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html)
says that I should be able to format my YAML header like this:
---
title: "Sample Document"
output: html_document
bibliography: newbiblio.bib
csl: apa.csl
---
However, when I do that, the file knits to a markdown (.md) file, but it is not processed into the output. I recieve this error:
pandoc-citeproc: 23:3-23:10: Expected end element for: Name {nameLocalName = "category", nameNamespace = Just "http://purl.org/net/xbiblio/csl", namePrefix = Nothing}, but received: EventEndElement (Name {nameLocalName = "info", nameNamespace = Just "http://purl.org/net/xbiblio/csl", namePrefix = Nothing})
pandoc: Error running filter /Applications/RStudio.app/Contents/MacOS/pandoc/pandoc-citeproc
Filter returned error status 1
Error: pandoc document conversion failed with error 83
Execution halted
The contents of my .bib file are:
#Article{Boettiger_2013,
doi = {10.1098/rspb.2013.1372},
url = {http://dx.doi.org/10.1098/rspb.2013.1372},
year = {2013},
month = {jul},
publisher = {The Royal Society},
volume = {280},
number = {1766},
pages = {20131372--20131372},
author = {C. Boettiger and A. Hastings},
title = {No early warning signals for stochastic transitions: insights from large deviation theory},
journal = {Proceedings of the Royal Society B: Biological Sciences},
}
I also do not understand why the biblio-style option in the YAML header does not to do anything. Essentially, all I need is a way to use a custom citation style I have already made with a markdown document. Any help would be greatly appreciated!
Without a reproducible example, it is hard to know exactly what is happening, but it looks like you are mixing two different configurations.
Method 1: Specifying a custom CSL file
The method of using a CSL file only works if you are using pandoc-citeproc. For example, I have downloaded the IEEE style, and saved it in the same directory as my RMarkdown file as ieee.csl. This MWE builds a separate bibliography file:
---
output: pdf_document
bibliography: test.bib
csl: ieee.csl
---
```{r}
knitr::write_bib(x = c("knitr", "rmarkdown") , file = "test.bib")
```
Some ref [#R-knitr]
Some again [#R-knitr]
Another ref [#R-rmarkdown]
# References
Method 2: Specifying styles in Natbib
If you want to use natbib to build the citations and bibliography, you have to use the biblio-style option. This following example should work without downloading anything:
---
output:
pdf_document:
citation_package: natbib
bibliography: test.bib
biblio-style: humannat
---
```{r}
knitr::write_bib(x = c("knitr", "rmarkdown") , file = "test.bib")
```
Some ref [#R-knitr]
Another ref [#R-rmarkdown]
# References
Unless you have a particular reason, I would probably go down the route of using pandoc-citeproc and a csl file. It integrates well with the RMarkdown world. Using Natbib just gets a bit more confusing, and from my experience is more prone to throwing errors.
I was having the same error message you are having (pandoc-citeproc: ParseError {errorContexts = [], errorMessage = "Failed reading: takeWhile1"...). And I discovered the solution conveying information from two other internet forums. Basically, the problem was that I had downloaded my custom citation "csl" file from GitLab in a way that it was an HTML version of the original raw xml file. I had to download the raw xml file instead. When I googled the error, I saw that many people was having the same issue.
Within Git-page, where you downloaded your "csl" file from, instead of clicking in the download button, you should right click in the "open raw" button, and then, "save link as". Then it should work.
In the below image, instead of clicking in button "1", right click in button "2" and save the link as:

Resources