Suppose that the command isn't important enough to have it on the separate line, But I still want it to be visible along the result, I know there is ` r inlinestr` in R Markdown, but it I can't pass echo=T to it. I want the result to be something like this:
You could use backticks, which would give you the monospace font, but not the gray background shading:
f. There are `sum(is.na(df$Height)) =` `r sum(is.na(df$Height))` missing Height values.
I just ran across this question that I attempted to answer about two years ago and thought of a way to get both the code and its evaluated output in a single inline statement. We just need a helper function. Below is an example. The code is entered as a text string and the function returns both the code and the result of evaluating the code:
---
title: "RMarkdown teaching demo"
author: "whoever"
output: pdf_document
---
```{r}
fnc = function(expr) {
paste(expr, " = ", eval(parse(text=expr)))
}
# Add some missing values
iris$Sepal.Length[c(3,5,10)] = NA
```
f. There are `r fnc("sum(is.na(iris$Sepal.Length))")` missing height values.
Below is the output.
It works, but there are two issues. First, the code is not in monospace font. Second, the code is not highlighted with a gray background.
I thought that I could get monospace font with the latex \texttt{} tag.
```{r}
fnc = function(expr) {
paste("\\texttt{", expr, " = ", eval(parse(text=expr)), "}", sep="")
}
```
This appears to return the desired string when run interactively ("\\texttt{sum(is.na(iris$Sepal.Length)) = 3}"), but throws the following error when I try to knit the document:
! Extra }, or forgotten $.
<recently read> \egroup
l.163 ...texttt{sum(is.na(iris$Sepal.Length)) = 3}
I thought I could get highlighting with the \hl{} tag (which also requires \usepackage{color, soul} in the latex header):
```{r}
fnc = function(expr) {
paste("\\hl{", expr, " = ", eval(parse(text=expr)), "}", sep="")
}
```
However, once again, this throws an error:
! Argument of \SOUL#addmath has an extra }.
<inserted text>
\par
l.161 ...re \hl{sum(is.na(iris$Sepal.Length)) = 3}
Both texttt{} and \hl{} work without a problem when used with regular text inside an rmarkdown document.
So, I'm not sure how to get the monospace font or highlighted text, but at least this takes a step toward code + evaluated code from a single inline R statement. Hopefully, someone with more knowledge of computing on the language and outputting latex markup can provide more insight into how to get this to work as desired.
Related
I have a somewhat complicated R function (different parts refer to various equations I'd like to explain.)
I want to write my code using R Markdown, but I need to be able to explain the different parts of the function in the document. A bit like literate programming.
I wonder if it is possible to split the function definition across different code chunks, or maybe insert markdown comments inside the function definition?
I'd like the end result to look something like this:
complicated = function(x) {
I use x^2 in the example so it is math, and yet short. Here it is in the actual R code:
x^2
}
This doesn't work:
``` {r}
complicated = function(x) {
```
explain the function with some math $x^$.
``` {r}
x^2
}
```
The following actually does work:
``` {r chunk1, echo=FALSE}
complicated=function(x) {
x^2
}
```
``` {r chunk1, echo=1:2, eval=F}
```
In the complicated function I use x^2 as an example.
Though it is a bit tricky, because if lines in the function change, I have to edit everything again. Also in the Rmd file, you don't actually see the code described by the comments.
Note:
Maybe it is possible to somehow have the relevant chunks written to a file without being evaluated, and then the file read in? I didn't manage to figure out a way yet...
Here's one way, though I admit it's a little bit of a hack.
---
title: "Split Function"
output: html_document
---
```{r funcdef}
myfunc <- function(x) {
x <- x + 1
x <- x * 2
return(x)
}
```
```{r funcdef1, echo = FALSE, eval = FALSE, include = FALSE}
x <- NULL
x <- x + 1
x <- x * 2
return(x)
```
First line:
```{r funcdef1, echo=2, eval = FALSE}
```
Now the last two:
```{r funcdef1, echo=3:4, eval = FALSE}
```
Done!
Explanation:
the first chunk funcdef is the full function definition, needed if we want to use it;
the second chunk includes the first line (that I do not echo, omitted with echo=-1) that is there so that the others do not err with 'x' not found (even if I do not eval or include); notice that it uses the same chunk name and has nothing in it
same for the third chunk
the reason I have to break out the body of the function without the function header and enclosing braces is that echo= using numbers allows us to subset which expressions are included, not which lines ... and a function declaration is one expression
Two things I don't really like about this:
It requires you to include the body of the function twice, so maintenance has more overhead than required;
It thinks x is being used, when all I really want is to reference the code.
Frankly, this may not be much better than including the portions of code within each subsequent chunk (and set eval=FALSE).
I found a nice answer to this question, though it looks a bit like a knitr bug. I hope it doesn't get fixed. It turns out that references to chunks work in Rmd just like in Rnw. You just have to use <<chunk name>> to refer back to a chunk.
So, here is the answer:
```{r Xsquare, eval=F}
x^2
```
We just need to take x and raise it to the second power: $x^2$.
Now let us put it together:
```{r complicated, eval=T}
complicated = function(x) {
<<Xsquare>>
}
```
Simple, right?
Turns out in Rstudio it works only when we knit everything together, but not on running a single chunk. Almost makes sense.
To solve this, in run the following: knit("filename.Rmd") in the console.
I have a character vector containing ampersand (&) that displays correctly when used outside LaTeX environment, such as \begin{itemize}.
This works:
---
output:
pdf_document
---
`r "Guns & Roses"`
The above code runs without error, meaning that either knitr or rmarkdown escapes the ampersand automatically.
Now, when the same R character vector with ampersand is specified inside LaTeX environment, following error is thrown: ! Misplaced alignment tab character &.:
---
output:
pdf_document
---
\begin{itemize}
\item `r "Guns & Roses"`
\end{itemize}
The reason why the first snippet in the question runs without errors but the second does not is that the & needs to be escaped in LaTeX and pandoc escapes it in the first case but not in the second.
This is because pandoc (with the extension raw_tex) doesn't escape "material between the begin and end tags".
knitr's output hook inline can be used to solve the problem.
One solution—that works for the OP, according to the comments—is to enclose output from R inline expressions in a verbatim environment where the & characer is allowed.
---
output:
pdf_document
---
```{r, echo = FALSE}
knitr::knit_hooks$set(inline = function(x) {
return(paste("\\verb|", x, "|"))
})
```
\begin{itemize}
\item `r "Guns & Roses"`
\end{itemize}
Alternatively, the following output hook for inline expressions could be used to replace all & by \&:
knitr::knit_hooks$set(inline = function(x) {
return(gsub(pattern = "&",
replacement = "\\&",
x = x,
fixed = TRUE))
})
I had a similar problem in Rmarkdown, where the Ampersand was supposed to show up in the labels of a ggplot. Using the output hooks CL suggested did not work for me. However, what did help was to put this specific ggplot into its own code chunk (note that I did not escape the ampersand! It is only part of a string variable)– Perhaps a strange workaround for Rmarkdown hickups but seems to work.
I know this question is similar to this one. But I couldn't get a solution there so posting it here again.
I want to get the exact same output as I get by clicking "Knit HTML" but via a command. I tryied using knit2html but it messes with the formatting and does not include the title, kable does not work etc.
Example:
This is my test.Rmd file,
---
title: "test"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(knitr,quietly=T)
kable(summary(cars))
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Output:
Knit HTML
knit2html
The documentation tells us:
If you are not using RStudio then you simply need to call the rmarkdown::render function, for example:
rmarkdown::render("input.Rmd")
Note that in the case using the “Knit” button in RStudio the basic mechanism is the same (RStudio calls the rmarkdown::render function under the hood).
In essence, rmarkdown::render does a lot more setup than knitr::knit2html, although I don’t have an exhaustive list of all differences.
The most flexible way of rendering the output is, at any rate, to supply your own stylesheet to format the output according to your wishes.
Please note that you need to set up Pandoc manually to work with rmarkdown::render on the command line.
That said, here are two remarks that would improve the knitr::knit2hmtl output, and that are superior to using rmarkdown::render in my opinion:
To include the title, use a Markdown title tag, not a YAML tag:
# My title
To format tables, don’t use the raw kable function. In fact, this is also true when using rmarkdown::render: the alignment of the table cells is completely off. Rmarkdown apparently uses centering as the default alignment but this option is almost never correct. Instead, you should left-align text and (generally) right-align numbers. As of this writing, Knitr cannot do this automatically (as far as I know) but it’s fairly easy to include a filter to do this for you:
```{r echo=FALSE}
library(pander)
# Use this option if you don’t want tables to be split
panderOptions('table.split.table', Inf)
# Auto-adjust the table column alignment depending on data type.
alignment = function (...) UseMethod('alignment')
alignment.default = function (...) 'left'
alignment.integer = function (...) 'right'
alignment.numeric = function (...) 'right'
# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
if (is.data.frame(object) ||
is.matrix(object)) {
# Replicate pander’s behaviour concerning row names
rn = rownames(object)
justify = c(if (is.null(rn) || length(rn) == 0 ||
(rn == 1 : nrow(object))) NULL else 'left',
sapply(object, alignment))
pander(object, style = 'rmarkdown', justify = justify)
}
else if (isS4(object))
show(object)
else
print(object)
})
```
In R, using knitr, is there a way to prevent line breaks in the HTML when results='hide' and echo=FALSE?
In this case:
First I do this,
```{r results='hide', echo=FALSE}
x=4;x
```
then I do that.
I get:
First I do this,
then I do that.
with both a break and an extra line between.
I'd like to get:
First I do this, then I do that.
instead.
Generally speaking, I'd like for code chunks to not insert new lines so that markdown is free to eat the one after the first line of text.
Thanks,
I assume you're creating an HTML document from an R Markdown document. In that case, you can use the inline R code capability offered by knitr by using the ` characters starting with the letter r.
Example:
In your R Markdown, write:
First I do this,`r x=4` then I do that. I can call x by doing `r x`.
And as output, you get:
First I do this, then I do that. I can call x by doing 4.
Note that in my example, I evaluated the variable x, but if you do not want to evaluate it, you do not have to. The variable x should still be assigned a value of 4 from the
`r x=4`
part of the R Markdown.
This is Inline R Code, and is documented here under the section "Inline R Code".
EDIT:
Note that Inline R Code has properties that are analogous to "echo=FALSE". And if you want to hide the results from inline R code, you can use base R functions to hide the output. See this question.
Try something like:
``` {r , results="asis", echo=F, eval=T}
if(showMe){
cat("printed")
} else {
cat("<!-- no break line -->")
}
```
I cannot find information on whether it is possible to specify options for inline chunks in knitr. I've just tried specifying them, as in the regular chunk, but this gives an error.
What I need is to include R code with highlighting in a PDF, but without evaluating it. This can only happen with inline chunks due to the format of the context. Or perhaps there is another way to include highlighted code.
To provide an example, I need something in the lines of:
Some text about something with `r eval=FALSE 1+1` inside the sentence.
This particular syntax gives:
Error in parse(text = code, keep.source = FALSE) :
<text>:1:11: unexpected ','
1: eval=FALSE,
Thanks to Yihui you can do,
\documentclass{article}
<<setup, include=FALSE>>=
knit_hooks$set(inline = function(x) {
if (is.numeric(x)) return(knitr:::format_sci(x, 'latex'))
highr::hi_latex(x)
})
#
\begin{document}
the value of $\pi$ is \Sexpr{pi}, and the function to read a table is
\Sexpr{'read.table()'}.
<<test2>>=
rnorm(10)
#
\end{document}