I have an Rnw file (a large one) and I want to show all code used in an appendix.
It is suggested in some of the knitr examples (https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw, also a good MWE) that having a code block like this is the way:
<<Rcode, eval=FALSE, ref.label=all_labels()[-1],echo=TRUE, cache=FALSE>>=
#
This works fine except all the code chunks merge into each other and none are labelled.
On the other hand if I run purl(myfile.Rnw) it labels the code chunks and separates them by two lines, which makes things much easier to read.
Is there any way of automatically listing the code using the second approach in a report appendix? I know I can have a code chunk to run purl to produce myfile.R as part of my report, but how do I then show the code in myfile.R in my appendix?
Here's an example .Rnw file (called "example.rnw"):
\documentclass{article}
\begin{document}
<<a>>=
x <- 1:10
x
#
<<b>>=
y <- 10:1
y
#
<<c>>=
z <- 1:5
z
#
\clearpage
\input{example-purl.tex}
\end{document}
If you create a file in your working directory called "template.rnw" that just contains:
<<%sCHUNK_LABEL_HERE, eval=FALSE>>=
#
Then, you run:
stitch(purl("example.rnw",output="example-purl.r"),template="template.rnw")
knit("example.rnw")
Does that make sense? Basically, you're purling, stitching the purled code, knitting the original document, and then compiling the resulting LaTeX ("example.tex") that includes the knitting and purling. Everything should be formatted nicely (and consistently).
Related
I am have problems tyring to input a .Rtex file into my shareLatex project using the /input{file} or include{file} commands.
Is there a way to include this as you can do with other .tex files?
The file looks like this :
<<>>=
# Create a sequence of numbers
X = 2:10
# Display basic statistical measures
summary(X)
#
The code is compiled if I put it in the main.Rtex file, but not if I try to include it. This questions is similar to the one on tex.stackexchange.
The following works in Overleaf (main file named *.Rtex).
\documentclass{standalone}
\begin{filecontents*}{tmp999.Rtex}
<<>>=
rnorm(3)
#
\end{filecontents*}
\begin{document}
\input{tmp999}
\end{document}
Instead of \input or \include, you have to use knitr's knit_child function. For this to work, both, the main file and the file containing the R code must have the .Rtex file extension. Other files can keep .tex. For your example, this would look like:
main.Rtex
\documentclass[]{article}
\begin{document}
\Sexpr{knit_child('content/knitr-child.Rtex')}
\end{document}
content/knitr-child.Rtex
<<>>=
# Create a sequence of numbers
X = 2:10
# Display basic statistical measures
summary(X)
#
I posted a similar answer to your linked question on tex.stackexchange.com.
When I purl() a .Rnw or .Rmd file, the resulting .R file has a commented line for each chunk that includes the chunk title and options for that particular chunk. I would like to distribute the .R file for a lecture, and think the extra lines, particularly the chunk options, are distracting for students. For example the chunk:
<<my_chunk, eval=FALSE>>=
x <- 1 + 2
#
ends up looking like:
## ----my_chunk, eval=FALSE------------------------------------------------
x <- 1 + 2
in the purled file. I would like to completely eliminate the commented line, or at the very least, the chunk options (i.e., eval=FALSE). What is the most straightforward way to do that? I did not have this issue with a previous version of knitr.
There are a few questions about this already, but they are either unclear or provide solutions that don't work, perhaps because they are outdated:
Proper R Markdown Code Organization
How to source R Markdown file like `source('myfile.r')`?
http://yihui.name/knitr/demo/externalization/
Modularized code structure for large projects
R Markdown/Notebook is nice, but the way it's presented, there is typically a single file that has all the text and all the code chunks. I often have projects where such a single file structure is not a good setup. Instead, I use a single .R master file that loads the other .R files in order. I'd like to replicate this structure using R Notebook i.e. such that I have a single .Rmd file that I call the code from multiple .R files from.
The nice thing about working with a project this way is that it allows for the nice normal workflow with RStudio using the .R files but also the neat output from R Notebook/Markdown without duplicating the code.
Minimal example
This is simplified to make the example as small as possible. Two .R files and one master .Rmd file.
start.R
# libs --------------------------------------------------------------------
library(pacman)
p_load(dplyr, ggplot2)
#normally load a lot of packages here
# data --------------------------------------------------------------------
d = iris
#use iris for example, but normally would load data from file
# data manipulation tasks -------------------------------------------------
#some code here to extract useful info from the data
setosa = dplyr::filter(d, Species == "setosa")
plot.R
#setosa only
ggplot(setosa, aes(Sepal.Length)) +
geom_density()
#all together
ggplot(d, aes(Sepal.Length, color = Species)) +
geom_density()
And then the notebook file:
notebook.Rmd:
---
title: "R Notebook"
output:
html_document: default
html_notebook: default
---
First we load some packages and data and do slight transformation:
```{r start}
#a command here to load the code from start.R and display it
```
```{r plot}
#a command here to load the code from plot.R and display it
```
Desired output
The desired output is that which one gets from manually copying over the code from start.R and plot.R into the code chunks in notebook.Rmd. This looks like this (some missing due to lack of screen space):
Things I've tried
source
This loads the code, but does not display it. It just displays the source command:
knitr::read_chunk
This command was mentioned here, but actually it does the same as source as far as I can tell: it loads the code but displays nothing.
How do I get the desired output?
The solution is to use knitr's chunk option code. According to knitr docs:
code: (NULL; character) if provided, it will override the code in the
current chunk; this allows us to programmatically insert code into the
current chunk; e.g. a chunk option code =
capture.output(dump('fivenum', '')) will use the source code of the
function fivenum to replace the current chunk
No example is provided, however. It sounds like one has to feed it a character vector, so let's try readLines:
```{r start, code=readLines("start.R")}
```
```{r plot, code=readLines("start.R")}
```
This produces the desired output and thus allows for a modularized project structure.
Feeding it a file directly does not work (i.e. code="start.R"), but would be a nice enhancement.
For interoperability with R Notebooks, you can use knitr's read_chunk method as described above. In a notebook, you must call read_chunk in the setup chunk; since you can run notebook chunks in any order, this ensures that the external code will always be available.
Here's a minimal example of using read_chunk to bring code from an external R script into a notebook:
example.Rmd
```{r setup}
knitr::read_chunk("example.R")
```
```{r chunk}
```
example.R
## ---- chunk
1 + 1
When you execute the empty chunk in the notebook, code from the external file will be inserted, and the results displayed inline, as though the chunk contained that code.
As per my comment above, I use the here library to work with projects in folders:
```{ r setup, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(here)
insert <- function(filename){
readLines(here::here("massive_report_folder", filename))
}
```
and then each chunk looks like
```{ r setup, echo=FALSE, message=FALSE, warning=FALSE,
results='asis', code=insert("extra_file.R")}
```
I have a R Markdown file that has my notes and chunks of code. I now want to write a R Sweave(Knitr) document to publish a paper using those chunks. I do not want to cut and paste the chunks, I rather call them directly. That way if I update the chunks, I don't have to do it in two places. It seems like it would be simple enough, but I can not figure it out. My code is as follows, test.rmd is my mark down document, foo is the chunk in the rmd file.
Test.rnw
<<Setup>>===
read_chunk('test.rmd')
#
<<foo>>==
#
Test.rmd
```{r foo, echo=TRUE}
print(summary(cars))
```
I would expect a summary of cars to be displayed in the output of the compilation of test.rnw into a PDF. But I don't. Any help is greatly appreciated.
read_chunk reads chunks from r script so call purl before read_chunk:
<<Setup>>=
knit_patterns$set(all_patterns[["md"]])
purl("test.Rmd")
knit_patterns$set(all_patterns[["rnw"]])
read_chunk("test.R")
#
<<foo>>=
#
I am making my first steps with knitr, trying to generate a raport. In the raport, I include R code which generates a ggplot2 object that I want to be included directly below some text. To make it more detailed, the graphic is a pair of two separated plots, which I want to be placed parallelly, one next to another.
So far, I have been dealing with by using the R code: producing and saving a .pdf picture, and then reading this picture from file and including it in the report by \includegraphics command. However, it is no more a solution for me - I want the plot to be generated simultaneously with the report by the R code (in particular: not to be saved anywhere as a .pdf)
However, the code I tried to use did not work properly - it generates the 2 plots, but they are however:
1) incorrectly placed - 2 pages below (which is even not the end of the document!)
2) I don't know how to place them in one row, with the defined size.
Please be of some help! Thank you in advance!! [below my not working porperly R code]
\textit{Pic 1 title} Some pic description
\begin{figure}[h]
\subfigure[pic1 name]{
<<echo = F, eval = T, message=F, fig=TRUE>>=
# a function returning a ggplot2 object (with a proper parameters instead of "...")
plot.matrix.from.file(...)
#
% below there is a fragment of the code I used before (which includes a graphics directly from a .pdf file)
%\includegraphics[scale=0.4]{data/simulated.data/obs_pred_mean_Gini_r.pdf}
\label{pic1 label}
}
\subfigure[pic2 name]{
<<echo = F, eval = T, message=F>>=
# a function returning a ggplot2 object (with a proper parameters instead of "...")
plot.matrix.from.file(...)
#
% below there is a fragment of the code I used before (which includes a graphics directly from a .pdf file)
%\includegraphics[scale=0.4]{data/simulated.data/obs_pred_var_Gini_r.pdf}
\label{pic2 label}
}
\caption{caption for the pair of plots}
\end{figure}
I do not see any problems using the subcaption package. See example 104.
\documentclass{article}
\usepackage{subcaption}
\begin{document}
You can include sub-figures using the \textbf{subcaption} package. For example,
Figure \ref{fig:test} contains \ref{fig:test-a} and \ref{fig:test-b}.
\begin{figure}
\begin{subfigure}{.5\textwidth}
<<test-a, echo=FALSE, results='asis', fig.width=5, fig.height=5>>=
plot(1:10)
#
\caption{This is Figure a. \label{fig:test-a}}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
<<test-b, echo=FALSE, results='asis', fig.width=5, fig.height=5>>=
plot(rnorm(100))
#
\caption{This is Figure b. \label{fig:test-b}}
\end{subfigure}
\caption{This figure contains two subfigures. \label{fig:test}}
\end{figure}
\end{document}
Output as expected: