Bash Variables not working in R Markdown - r

I'm using a chunk of bash code in my R Markdown document (.Rmd).
A minimal example looks like this:
```{bash}
MY_NAME='Fred'
echo $MY_NAME
```
When I knit this, I get no output, meaning, the variable is not recognized.
When I do the same in my Unix console, it outputs 'Fred'. Any hint as to why the variable doesn't seem to be stored?

Related

Rmarkdown, pandoc/PDFlatex, and underscores in a temporary directory name - a problem

I have an R markdown document that has a chunk that generates a plot using ggplot2 and a custom function, progress.plot. The chunk looks like this
```{r charts, echo=FALSE, fig.cap="Your progress curve"}
progress.plot(student)
```
This document generates a PDF using a LaTeX engine. I think it uses PDFlatex via pandoc. This is causing a problem.
It seems like Rmarkdown uses a temporary folder to store the diagram I generate with ggplot2. The name of that folder has underscores. This means the path to the graphic file, a string that's used in the .tex source file, has an underscore. And the latex compiler doesn't like that.
! Missing $ inserted.
<inserted text>
$
l.142 ...de2020-05-06_files/figure-latex/charts-1}
\caption[Your progress cu...
I am getting a "Missing $ inserted" error before the latex compiler craps out. No PDF is generated and the directory with the figure is deleted. (I have experience with LaTeX, so I'm familiar with this type of troubleshooting.)
Is there a way to take the underscore out of the temporary directory's name? Or is there any other workaround that will allow me to generate figures to include in my R markdown document?
Thanks for whatever advice people can share.

Code / Process for running rmarkdown in base R

All my codes developed in base R and I don't want to use RStudio, however I want to use rmarkdown feature in base R which is available in Rstudio.
I have downloaded rmarkdown package in base r, but not able to derive a code to publish my work
All the output of my codes written in R should be view able through web browser.
First make sure you're using .Rmd as your file extension. If not, rename it to a .Rmd extension. Make sure you have Pandoc installed on your OS.
Next, add the following to the top of the file:
---
title: "Your notebook title"
output: html_document
---
output: could take any value. You can pass in the value of ioslides_presentation for example if you want but it looks like html_document fits the criteria of what you want pretty well.
Once you have that, write your code in any editor (or the R console if you prefer). Use the code chunks and markdown text formatting as you normally would:
```{r}
plot(1:10)
```
In my base R Console, this is how mynotebook.Rmd looks like:
Finally, use the render() function from rmarkdown. You can either attach it and run render():
library(rmarkdown)
render("mynotebook.Rmd")
Or, run rmarkdown::render("mynotebook.Rmd").
Notice that the use of RStudio is not required at all since Pandoc is the document converter performing this task. For the so inclined, this is what its documentation has to say:
When you run render, R Markdown feeds the .Rmd file to knitr,
which executes all of the code chunks and creates a new markdown (.md)
document which includes the code and it's output.
The markdown file generated by knitr is then processed by pandoc
which is responsible for creating the finished format.
This may sound complicated, but R Markdown makes it extremely simple
by encapsulating all of the above processing into a single render
function.

run an R Markdown (check.Rmd ) and an R knitr (test.Rnw ) file together

I have the following problem; There are 2 big documents, one written in R Markdown (check.Rmd ) and the other in R knitr (test.Rnw ). In the first doc we have a code like the following:
\section{Organisations Test}
\textbf{Running Organisations Checks}
<<CreateOrganisations, echo=FALSE, progress=TRUE, warning=FALSE, eval=TRUE>>=
source("OrganisationsTest.R")
OrganisationsTest(current_schema,server,user,pass)
#
and in the other as follows:
2. check the downwards shock
```{r chunk_Int_Sh_p2, echo=FALSE}
unique(param.int.shock.tab[SHOCKTYPE=="SHOCK_DOWN"&PERIODEND<21|PERIODEND==90, list( Maturity=PERIODEND, Shock_value=100*SHOCKVALUE)])
```
Now the question: how can I combine both so that I have just one script which runs and compile both one after each other. Just for clarification, I mean without any changes in both documents how can I have just one script which applyes to the first doc knit PDF to create pdf and to the other one CompilePDF ?
I suppose in Linux one can write a shell script but what a bout using RStudio in windowes?
I am really grateful for every hint I am a little bit helpless!
Addendum: In principle it is as follows: we have 2 files if you would compile a knitr file you would use bottom in RStudio, and for a Markdown file one may use bottom in RStudio, BUT we want to put both together and klick on one bottom. How is it possible?
The RStudio buttons "Compile PDF" (for RNW documents) and "Knit PDF" (for RMD documents) are convenient, but in cases like this one it is important to understand what they do in order to reproduce the same or similar behavior.
Summing the question up, it asks for a way to convert two files (a RMD and a RNW document) to PDF, preferably using a button like the two buttons mentioned above.
Unfortunately, (up to my knowledge) it is not possible to add any user-defined buttons to the RStudio GUI. But it is straightforward to write an R script that compiles both documents.
In the following I assume two files:
first.Rmd:
This is a RMD file.
```{r, echo=FALSE}
plot(1)
```
second.Rnw:
\documentclass{article}
\begin{document}
This is a RNW file.
<<>>=
plot(1)
#
\end{document}
To compile first.Rmd to PDF, we need the following (see How to convert R Markdown to PDF?):
library(knitr)
library(rmarkdown)
knit(input = "first.Rmd")
render(input = "first.md", output_format = "pdf_document")
The knit call generates first.md from first.Rmd, execting the R code in the chunks. render converts the resulting markdown file to PDF. [Note the addendum at the bottom!]
To compile first.Rnw to PDF, we can simply use knit2pdf:
knit2pdf("second.Rnw")
Copying both snippets into one R script and clicking "Source" is as close as possible to a "one-button-solution".
However, note that the snippets do something very similar to the "Compile / knit PDF" button, but it is not identical. The "Compile" buttons start a new R session while the solution above uses the current session.
Before executing the snippets make sure to use the correct working directory.
Both knit and knit2pdf by default use envir = parent.frame(). That means R code in chunks is executed in the calling enironment (see What is the difference between parent.frame() and parent.env() in R). This can be a useful feature, for example to "pass" variables to chunks, but it is important to know about it. Otherwise a document might compile just fine in one session (where certain variables exist in the calling environment) but cannot be compiled in another session (that is missing these variables). Therefore, this feature is a little bit dangerous in terms of reproducibility. As a solution, envir = new.env(parent = as.environment(2)) could be used; see knitr inherits variables from a user's environment, even with envir = new.env() for more details on that topic.
I just realized to following about render:
If the input requires knitting then knit is called prior to pandoc.
(Source: ?render)
Therefore, knit(input = "first.Rmd"); render(input = "first.md", output_format = "pdf_document") can be simplified to render(input = "first.Rmd", output_format = "pdf_document"). The envir issues of knit from above apply to render as well.

There are no figures in the word and pdf outputs when using RStudio and opts_chunk$set(fig.align='center') [duplicate]

I'm using knitr to create a markdown file from Rmd and I have the following option set at the top of my .Rmd script to hide all results and plots:
```{r, echo=FALSE}
opts_chunk$set(results="hide", fig.show="hide")
```
When I hit the Knit HTML button in RStudio, this works - I get output without the results and figures. But if I run from the command line:
Rscript -e 'knitr::knit("myfile.Rmd")'
It appears the opts_chunk$set() line isn't read, and I get results and plots in my .md output. I've worked around the problem by specifying these options in the Rscript command:
Rscript -e 'library(knitr); opts_chunk$set(results="hide", fig.show="hide"); knit("myfile.Rmd")'
But I'd rather keep all the options read from the file I'm using rather than specified at the command line. How do I get the options read in the .Rmd file when kniting with Rscript at the command line?
Thanks.
I think you need to add
library("knitr")
to the chunk (you might want to set message=FALSE in the chunk options for that chunk).
The problem is that when you do
Rscript -e 'knitr::knit("myfile.Rmd")'
you're not actually attaching the knitr package, which means it isn't in the search path for functions, which means that R can't find the opts_chunk object.
Using knitr::opts_chunk might work too ...
as you suggested, so does Rscript -e 'library("knitr"); knit("myfile.Rmd")'
When you click the button in RStudio, RStudio automatically loads knitr in the environment in which it runs knit().

knitr does not inject the R output into a pandoc/markdown documemt

I'm trying to use knitr to inject R code and its output in pandoc/markdown documents. But I do not get knitr to inject the R output. I have tried decorating the R chunks with r and with{r}. Both doesn't work. Here my sample setup (with ```r):
First I show the command I issue, then I list the two files subsequently used by this command.
Here the command for the shell:
$ r CMD BATCH knitme.R
Content of knitme.R:
library("knitr")
pandoc("foo.md")
Content of foo.md:
# My knitr test
```r
1+1
```
Did this print *the result* as well?
Here a graph:
```r
plot(1:10)
```
And where is the graph?
After I ran the command I do get, as expected a new file foo.html. Here its content:
<h1 id="my-knitr-test">My knitr test</h1>
<pre class="sourceCode r"><code class="sourceCode r"><span class="dv">1+1</span></code></pre>
<p>Did this print <em>the result</em> as well?</p>
<p>Here a graph:</p>
<pre class="sourceCode r"><code class="sourceCode r">
<span class="kw">plot</span>(<span class="dv">1</span>:<span class="dv">10</span>)</code></pre>
<p>And where is the graph?</p>
This result shows that pandoc converted the input file foo.md, *but knitr did not inject the Output of the execeutes R code.
What do I miss? any help appreciated!
You should first call knit() on an R Markdown (*.Rmd) document, which produces a Markdown (*.md) document, and that is when you can run pandoc().
library(knitr)
knit('foo.Rmd')
pandoc('foo.md')
The R scripts in examples 084 and 088 as mentioned on the flaky website have illustrated how. Please also take a look at the Rmd documents to learn the syntax for R code chunks in R Markdown. If you still have 5 minutes, watch the video on the homepage, and I think all the confusion should be gone.

Resources