Using R Markdown chunks in R Sweave(Knitr) - 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>>=
#

Related

R Sweave: put the whole code of the .Rnw file in Appendix?

I just found this awesome technique to put the code used in the .Rmd file in the appendix (of that same file).
However, I am using R Sweave and not R Markdown and I would like to know if there exists a similar way to put all the code at the end in a unique chunk. The code to do that in Markdown does not work in Sweave. I precise that, unlike this post, I do not have a separate .R file where the calculations are made. Everything is done in the .Rnw file.
Does anybody know how to do it?
Edit : a reproducible example
\documentclass[11pt, twocolumn]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<reg2, echo=FALSE, print=FALSE>>=
head(mtcars)
#
<<reg3, echo=FALSE, print=FALSE>>=
head(iris)
#
\section*{Appendix}
% the place where I could like to put the whole code
\end{document}
This chunk works to include the code:
<<echo=FALSE, eval=TRUE>>=
filename <- tempfile(fileext=".R")
Stangle("test.Rnw", output = filename, quiet = TRUE)
cat(readLines(filename), sep = "\n")
#
When I include that in your example file, I see this:
I think it's possible to modify the format a bit; see ?Rtangle for some details. Similar things are possible with knitr, but it's more flexible. I suspect the best method would be similar to the one you found for RMarkdown.

Is it possible to source multiple external chunk from a file in Knitr/ Rmarkdown?

I have an R-script file script.r as,
## ---- Chunk-1 ----------
x <- rnorm(1000)
## ---- Chunk-2 ----------
hist(x)
Now in my rmarkdown document doc.rmd, I can read the script.r file as,
knitr::read_chunk("script.r")
I can execute both the chunks as follows,
```{r Chunk-1}
```
```{r Chunk-2}
```
Is there anyway, I can execute Chunk-1 and Chunk-2 together. In my real situation, I have lots of chunks, and I want them separate in script file but I need some of them execute together in the Rmd file. I am wondering if there is any easier approach rather than repeating blank chunk block.
Maybe I am missing something but I do not see the goal of using your script.r file as chunks. When looking at your example, if you want to execute your script.r file in your Rmd file, you can directly use source('script.r').
Except if you want to execute some chunks based on conditions for instance. In that aim, do you know that you can call a complete external Rmd file as a child document ?
Your child-script.Rmd:
```{r Chunk-1}
x <- rnorm(1000)
```
```{r Chunk-2}
hist(x)
```
Your main Rmd script:
Some markdown text
```{Call_child, child='./child-script.Rmd'}
```
Some other markdown text

Modularized R markdown structure

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")}
```

Passing values from an Rnw file to an R script

Since I am a newbie as far as knitr is concerned, I am reading and modifying the examples given in knitr web site. One the approaches that caught my attention is to call chunks of an R script within an Rmw file. After compiling and modifying several examples, I wonder whether one can set a variable on an Rmw file and pass it to an R-script.
Here is an example
\documentclass{article}
\begin{document}
<<set-options, echo=FALSE, cache=FALSE>>=
options(replace.assign=TRUE)
opts_chunk$set(cache=TRUE, fig.show='asis')
read_chunk('simple_example.R')
#
\title{Example}
\author{Somebody}
\maketitle
\section{Print variable}
<<Print-data, echo=TRUE>>=
inp=2
#
\end{document}
and
# Simple Example
## ---- Print-data ----
inp=inp+2
print(inp)
The output result is ip=2 and an error msg "object inp not found".
Many thanks
The code chunk Print-data overrode the one in the Rnw file, so inp=2 was not executed, hence the error.
It seem you want to embed the chunk after Print-data:
<<>>=
inp=2
<<Print-data>>
#

How to convert .Rmd file to .Rnw file of Rstudio?

I really like using knitr in Rstudio and have been using it to write markdown presentations and data analysis. I want to use the same code and results in a paper and want to convert the code chunks in Rmd file ```{r} to the chunks of Rnw file << >>= #.
This allows using the same document and code written for presentation for the main paper as well.
Is there a way of converting between code chunks of markdown and Rnw files ?
or the entire file itself as apart from the difference in syntax of code chunks, they are quite similar in the markup (converting the text to latex is easy with say pandoc)
Instead of converting the whole document, you can just externalize your R code so it can be shared across different documents; see http://yihui.name/knitr/demo/externalization/
Once you have read_chunk('Rcode.r'), you can use ```{r label} in your Rmd and <<label>>= in your Rnw document, where label comes from the line ## #knitr label in the R script.

Resources