Goal
In an R/Markdown document that I want to convert to LaTeX I want to set knitr options so that the entire document uses plain code chunks for all code inputs by default. Thus, for a .Rmd document with
```{r}
x <- 1 + 1
```
I want to obtain the output
```
x <- 1 + 1
```
Using the highlight option
I had hoped that the highlight=FALSE option could be used for this but this generates text-chunks rather than plain chunks. More precisely, for the simple example above, knit() produces an R-chunk by default (i.e., with highlight = TRUE):
```r
x <- 1 + 1
```
After setting knitr::opts_chunk$set(highlight = FALSE) a text-chunk is produced:
```text
x <- 1 + 1
```
But what I would like to have a plain chunk without any special language, see above.
Combination with lang option
I can obtain what I want via
knitr::opts_chunk$set(highlight = TRUE, lang = "")
Thus, I do enable highlighting but set the lang to an empty string. This indeed yields the plain code I want to have.
There is at least one disadvantage, though (apart from the rather hacky feel of this solution). Namely, if in the same document I do want to enable highlighting in the options of one specific chunk, I have to set lang = "r" now instead of highlight = TRUE, e.g.,
```{r, lang="r"}
x <- 1 + 1
```
So I wonder whether there is a better solution for this?
Background
In older versions of pandoc (I tried 2.9.x) text-chunks were converted to {verbatim} code chunks in LaTeX output.
However, more recent versions of pandoc (I tried 2.17.x) text-chunks are converted to {Shaded} instead and only plain chunks are converted to {verbatim}.
Another hacky solution is (I don't even dare to explain it):
```{r}
knitr::opts_hooks$set(highlight = function(options) {
if (!options$highlight) {
options$highlight = TRUE
options$lang = ''
}
options
})
knitr::opts_chunk$set(highlight = FALSE)
```
```{r}
1 + 1
```
```{r, highlight=TRUE}
2 + 2
```
The language name text when highlight = FALSE is currently hard-coded in knitr, so you cannot change it: https://github.com/yihui/knitr/blob/907184f82/R/hooks-md.R#L171 I'm open to making it configurable, but I'm not sure how (I hope not to add a new chunk option for setting the language in the case of highlight = FALSE).
I'm not sure I entirely understand what you want, but does this in the yaml header help?
---
output:
html_document:
theme: null
highlight: null
---
Related
Suppose there is a code chunk as follows:
```{r mean diff}
(5-mean(dnorm(40,5,2))/5
```
I would like to be able to reference this code chunk with its label in inline form in a markdown document, so that the reference is replaced by the output of this chunk. Is there a way to do it?
" the difference is `r mean diff` %." ##something like this?
I think the answer to your question is "yes, but it's tricky". By default knitr doesn't save the last value computed in a code chunk. In regular code, the last value calculated is saved in .Last.value, but knitr doesn't simulate this.
However, a simple modification lets you do something very similar:
```{r}
meandiff <- 5-mean(dnorm(40,5,2))/5
meandiff # if you want the chunk to print its value
```
and then in the text, use
" the difference is `r meandiff` %."
If you really want to save the last value, it's possible by setting a "render hook". For example, the code below saves the last value, then calls the old hook:
```{r}
.Last.value <- NULL
old_hook <- knitr::opts_chunk$get("render")
knitr::opts_chunk$set(render = function(x, options, ...) {
.Last.value <<- x
if (!is.null(old_hook))
old_hook(x, options, ...)
else
knitr::knit_print(x, options, ...)
})
```
```{r mean diff}
5-mean(dnorm(40,5,2))/5
```
The value was `r .Last.value`.
There are already a few questions considering ggplots in RMarkdown but none has answered my question as how to put a ggplot into a table with kable() by knitr.
I ve tried this link:
How can I embed a plot within a RMarkdown table?
But have not had any luck so far. Any ideas?
The idea was to put all plots into a list with
a<-list(p1,p2,p3...)
and then having the table with
{r}kable(a)
Additional text should also be able to be included
b<-("x","y","z",...)
kable (c(a,b),col.names=c())
Thanks for your help
Frieder
I experimented some with this and the following is the best I could come up with. This is a complete markdown document you should be able to paste into RStudio and hit the Knit button.
Two relevant notes here.
Setting the file links directly into kable doesn't work as it is wrapped in html such that it is interpreted as text, so we need to gsub() it in. An alternative is to set kable(..., escape = FALSE), but it is a risk that other text might cause problems.
Also, the chunk option results = 'asis' is necessary to have the print(kab) return raw html.
I don't know if these are problems for the real application.
---
title: "Untitled"
author: "me"
date: "02/06/2020"
output: html_document
---
```{r, results = 'asis'}
library(ggplot2)
library(svglite)
n <- length(unique(iris$Species))
data <- split(iris, iris$Species)
# Create list of plots
plots <- lapply(data, function(df) {
ggplot(df, aes(Sepal.Width, Sepal.Length)) +
geom_point()
})
# Create temporary files
tmpfiles <- replicate(n, tempfile(fileext = ".svg"))
# Save plots as files, get HTML links
links <- mapply(function(plot, file) {
# Suit exact dimensions to your needs
ggsave(file, plot, device = "svg", width = 4, height = 3)
paste0('<figure><img src="', file, '" style = "width:100%"></figure>')
}, plot = plots, file = tmpfiles)
# Table formatting
tab <- data.frame(name = names(plots), fig = paste0("dummy", LETTERS[seq_len(n)]))
kab <- knitr::kable(tab, "html")
# Substitute dummy column for figure links
for (i in seq_len(n)) {
kab <- gsub(paste0("dummy", LETTERS[i]), links[i], kab, fixed = TRUE)
}
print(kab)
```
I have found my way around it as described in the link I posted.
I. Saved my plot as a picture
II. Used sprintf() to insert picture into table with this command from Rmarkdown:
![](path/to/file)
Poor, but it works. If anybody finds a solution, I will always be interested in smart coding.
Is there a way of showing formatter R output in rmarkdown/knitr when using results = 'asis'?
An example would be the following function:
myfun <- function() {
cat("hello!\n")
cat(c("one" = 1, "two" = 2))
}
Then, this chunk will print the second cat on a new row:
```{r}
myfun()
```
But this will ignore the formatting from myfun:
```{r, results = "asis"}
myfun()
```
Is there a way of keeping results='asis' but at the same time keep the output of myfun formatted as intended?
You can use the knitr chunk option results = "asis" if you are happy to add two or more spaces at the end of the line. That is, instead of "hello\n", you need to write "hello \n" to trigger the line break.
Example R Markdown code:
---
output: html_document
---
```{r}
myfun <- function() {
cat("hello! \n")
cat(c("one" = 1, "two" = 2))
}
```
```{r results = "asis"}
myfun()
```
Gives
Why the blank spaces? It's because two spaces at the end of a line are used to indicate a hard line break in markdown. For example, this quote is taken from Pandoc's Markdown (which is the default markdown flavour R Markdown uses):
Paragraphs
A paragraph is one or more lines of text followed by one or more blank lines. Newlines are treated as spaces, so you can reflow your paragraphs as you like. If you need a hard line break, put two or more spaces at the end of a line.
I am doing homework (yes) but this question is about the R Markdown I am using to render the answers, rather than the homework question itself. I hope that's fine.
When I use code chunks inside a ordered list (the problems are numbered so almost everything is in numbered lists), then ordered list items after it are rendered verbatim (so inline equations are rendered like: $\beta_0$ instead of showing the symbols) and don't wrap even though I have tidy=TRUE and width.cutoff set to 50. They run right off the page. They also aren't indented, which makes it further clear that they aren't getting evaluated as ordered list items. The width.cutoff option works for the code chunks but not for the ordered list items, for some reason. I can't find this error anywhere else online. I found these questions:
How to wrap code and the output in markdown (.Rmd)
knitr: How to prevent text wrapping in output?
In R markdown in RStudio, how can I prevent the source code from running off a pdf page?
but they all just seem to tell me to play with the width or width.cutoff options, which I have already done and aren't working. I attach some test code below and a screenshot of what the pdf comes out to be(link to disappointing image). As you can see, the a. part comes out fine, but b, c, and sub-questions do not. In the larger file, the top-level numbered list also has this problem. If anyone has any ideas please let me know.
Also, I don't know if this is important, but these lines show in RStudio in blue, unless I add another line break before them, in which case they turn back to black and thereafter alternate between blue and black. But the color doesn't seem to matter, they still get rendered the same way in the same place. I've tried double spaces at the ends of the previous lines, no change. The only thing that makes them not render as verbatim is to delete the new lines before them and allow them to be right next to the text line above them, but since they aren't indented this makes them look like they're part of the previous question and is problematic for reading. Thank you in advance for any help!
---
title: "TestThing"
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{amsmath,amsthm,amssymb,graphicx,epstopdf}
---
```{r echo=FALSE, warning=FALSE}
library(knitr)
library(foreign)
library(car)
library(xtable)
library(plyr)
library(reshape2)
```
```{r set-options, echo=FALSE, cache=FALSE}
options(width=50)
opts_chunk$set(comment = "", warning = FALSE, message = FALSE, echo = TRUE, tidy = TRUE, size="small", width.cutoff=50)
```
3. Problem 3
(a) Some amount of text.
Solving for $\hat{\beta}$:
\begin{equation}
\begin{aligned}
(y-X\hat{\beta})'(y-X\hat{\beta}) &= y'y - \hat{\beta}'X'y - y'X\hat{\beta} + \hat{\beta}'X'X\hat{\beta} \\
... \\
\hat{\beta} &= (X'X)^{-1}(X'y)
\end{aligned}
\end{equation}
This solution is well-defined if there is no perfect collinearity among variables (that is, __X__ has full rank).
(b) Text long enough to show that it runs off the page. Why would it do that? After all the width options I set for it... Show that the conditional expectation function yadda yadda etc. etc..
The Zero Conditional Mean Assumption sucks. Since the fitted value $\hat{y}$ is created using OLS estimation and $\hat{y} = X\beta$, E[y|X] = $X\beta$ when the Zero Conditional Mean assumption holds.
(c) Express the values in terms of things.
a. Express the values in terms of the conditional expectations of X and Y:
B = E[Y|X=1]
C = E[Y|X=0]
D = B-C = unit change in Y per increase of 1 in X
b. Express the values in terms of $\beta_0$ and $\beta_1$:
B = $\beta_0 + \beta_1$
C = $\beta_0$
D = $\beta_1$
c. Use the data to estimate B, C, D, $\beta_0$ and $\beta_1$:
```{r echo=FALSE, results="asis"}
datathing <- data.frame(X=c(0,0,1,1), Y=c(1,3,5,7))
print(xtable(summary(lm(datathing$Y ~ datathing$X))), comment=FALSE)
```
B = $\beta_0 + \beta_1$ = 2 + 4 = 6
C = $\beta_0$ = 2
D = $\beta_1$ = 4
Is there a standard way to include the computed values from variables early on in the written knitr report before those values are computed in the code itself? The purpose is to create an executive summary at the top of the report.
For example, something like this, where variable1 and variable2 are not defined until later:
---
title: "Untitled"
output: html_document
---
# Summary
The values from the analysis are `r variable1` and `r variable2`
## Section 1
In this section we compute some values. We find that the value of variable 1 is `r variable1`
```{r first code block}
variable1 <- cars[4, 2]
```
## Section 2
In this section we compute some more values. In this section we compute some values. We find that the value of variable 2 is `r variable2`
```{r second code block}
variable2 <- cars[5, 2]
```
A simple solution is to simply knit() the document twice from a fresh Rgui session.
The first time through, the inline R code will trigger some complaints about variables that can't be found, but the chunks will be evaluated, and the variables they return will be left in the global workspace. The second time through, the inline R code will find those variables and substitute in their values without complaint:
knit("eg.Rmd")
knit2html("eg.Rmd")
## RStudio users will need to explicitly set knit's environment, like so:
# knit("eg.Rmd", envir=.GlobalEnv)
# knit2html("eg.Rmd", envir=.GlobalEnv)
Note 1: In an earlier version of this answer, I had suggested doing knit(purl("eg.Rmd")); knit2html("eg.Rmd"). This had the (minor) advantage of not running the inline R code the first time through, but has the (potentially major) disadvantage of missing out on knitr caching capabilities.
Note 2 (for Rstudio users): RStudio necessitates an explicit envir=.GlobalEnv because, as documented here, it by default runs knit() in a separate process and environment. It default behavior aims to avoid touching anything in global environment, which means that the first run won't leave the needed variables lying around anywhere that the second run can find them.
Here is another approach, which uses brew + knit. The idea is to let knitr make a first pass on the document, and then running it through brew. You can automate this workflow by introducing the brew step as a document hook that is run after knitr is done with its magic. Note that you will have to use brew markup <%= variable %> to print values in place.
---
title: "Untitled"
output: html_document
---
# Summary
The values from the analysis are <%= variable1 %> and
<%= variable2 %>
## Section 1
In this section we compute some values. We find that the value of variable 1
is <%= variable1 %>
```{r first code block}
variable1 = cars[6, 2]
```
## Section 2
In this section we compute some more values. In this section we compute
some values. We find that the value of variable 2 is <%= variable2 %>
```{r second code block}
variable2 = cars[5, 2]
```
```{r cache = F}
require(knitr)
knit_hooks$set(document = function(x){
x1 = paste(x, collapse = '\n')
paste(capture.output(brew::brew(text = x1)), collapse = '\n')
})
```
This has become pretty easy using the ref.label chunk option. See below:
---
title: Report
output: html_document
---
```{r}
library(pixiedust)
options(pixiedust_print_method = "html")
```
### Executive Summary
```{r exec-summary, echo = FALSE, ref.label = c("model", "table")}
```
Now I can make reference to `fit` here, even though it isn't yet defined in the script. For example, a can get the slope for the `qsec` variable by calling `round(coef(fit)[2], 2)`, which yields 0.93.
Next, I want to show the full table of results. This is stored in the `fittab` object created in the `"table"` chunk.
```{r, echo = FALSE}
fittab
```
### Results
Then I need a chunk named `"model"` in which I define a model of some kind.
```{r model}
fit <- lm(mpg ~ qsec + wt, data = mtcars)
```
And lastly, I create the `"table"` chunk to generate `fittab`.
```{r table}
fittab <-
dust(fit) %>%
medley_model() %>%
medley_bw() %>%
sprinkle(pad = 4,
bg_pattern_by = "rows")
```
I work in knitr, and the following two-pass system works for me. I have two (invisible) code chunks, one at the top and one at the bottom. The one at the bottom saves the values of any variables I need to include in the text before they are actually computed in a file (statedata.R). The top chunk sets the variable values to something that stands out if they haven't been defined yet, and then (if it exists) it grabs the actual values from the stored file.
The script needs to be knit twice, as values will be available only after one pass through. Note that the second chunk erases the saved state file at the end of the second pass, so that any later changes to the script that affect the saved variables will have to be computed anew (so that we don't accidentally report old values from an earlier run of the script).
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE, results='hide'}
# grab saved computed values from earlier passes
if (!exists("variable1")) {
variable1 <- "UNDEFINED"
variable2 <- "UNDEFINED"
if (file.exists("statedata.R")) {
source("statedata.R")
}
}
# Summary
The values from the analysis are `r variable1` and `r variable2`
## Section 1
In this section we compute some values. We find that the value of variable 1 is `r variable1`
```{r first code block}
variable1 <- cars[4, 2]
```
## Section 2
In this section we compute some more values. In this section we compute some values. We find that the value of variable 2 is `r variable2`
```{r second code block}
variable2 <- cars[5, 2]
```
```{r save variables for summary,echo=FALSE,results='hide'}
if (!file.exists("statedata.R")) {
dump(c("variable1","variable2"), file="statedata.R")
} else {
file.remove("statedata.R")
}
```
Latex macros can solve this problem. See this answer to my related question.
\newcommand\body{
\section{Analysis}
<<>>=
x <- 2
#
Some text here
} % Finishes body
\section*{Executive Summary}
<<>>=
x
#
\body