Inline knitr print code not printing - r

How do I fix this?
Inline `r 41`. What about `r print(42)`? Finally, `r I(print(43))`.
When I run this through knit2html(), it prints 42 and 43 to the R console. The HTML file that's produced is missing the 42.
Inline 41. What about ? Finally, 43.
I just found this: https://github.com/yihui/knitr/blob/master/NEWS.md
MINOR CHANGES
for inline R code, the value is returned only if the R code prints a visible value, e.g. \Sexpr{x <- 1} will be empty, and \Sexpr{pi} will return the value of pi
I think this change is a mistake. Please revert it. I have a function that does the printing. Do I really need to wrap it in I() every time I use it?
I could wrap the print statements inside the function in I(), but that's a hack and it doesn't even work too well. What if I am using a third party function that does the printing?
Here is what happens when I wrap print statements inside the function in I():
my_print = function () {
I(print(142))
}
my_cat = function () {
I(cat(143, "\n"))
}
Markdown:
What `r my_print()` about `r my_cat()` this?
```{r}
my_print()
```
```{r}
my_cat()
```
Output:
What 142 about this?
my_print()
## [1] 142
## [1] 142
my_cat()
## 143
## list()
So this fixes it for inline use, but breaks for chunk use. But only for print. Cat doesn't even work for inline.

Related

Change color of error messages in RMarkdown code output (HTML, PDF)

Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.
---
title: ""
---
#### Example 1
```{r e1, error = TRUE}
2 + "A"
```
#### Example 2
```{r e2, error = TRUE}
2 + 2
```
In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.
1. Use a knitr hook
The preferred solution is to use the output hook for errors:
```{r}
knitr::knit_hooks$set(error = function(x, options) {
paste0("<pre style=\"color: red;\"><code>", x, "</code></pre>")
})
```
Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.
2. Quick and dirty solution using JS/jQuery
And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header.
Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.
<script type="text/javascript">
$(document).ready(function() {
var $chks = $("pre:not(.r) > code");
$chks.each(function(key, val) {
cntnt = $(this).html();
if (cntnt.indexOf("Error") != -1) {
$(this).css('color', 'red');
}
})
})
</script>
I stumbled here because I had the same question but for PDF output rather than HTML.
It turns out combining #Martin Schmelzer's Solution with some hints from #Yihui Xie found here helps to achieve the same behavior in a PDF output.
Add \usepackage{xcolor} to your YAML header and the following chunk to your .Rmd file.
```{r}
color_block = function(color) {
function(x, options) sprintf('\\color{%s}\\begin{verbatim}%s\\end{verbatim}',
color, x)
}
knitr::knit_hooks$set(error = color_block('red'))
```
The result is red error messages like

Having multiple pander()s in a function

How do I create multiple outputs via pander() in a knitted document "asis" ?
When I have multiple calls of pander in a function, only the most recent one is shown in the HTML output. Here's an example:
tmp = function() {
pander('A')
pander('B')
pander('C')
}
tmp()
In the knitted document this gives: C
I could set panderOptions('knitr.auto.asis', FALSE) or I could use cat() so that the pander() output is written to the standard output. But then it's formatted as code, not as part of the document. As I need pander() to format a few tables for me, this does not help.
The tmp function will return only the last object -- that's why only C is printed. If you want to write each object to the stdout right away without the auto-asis convenience option, then you have to both disable the option like you did and use the relate knitr chunk option, eg:
```{r results='asis'}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
tmp = function() {
pander('A')
pander('B')
pander('C')
}
tmp()
```
See more examples in the related "Using pander with knitr" vignette.

How to syntax highlight inline R code in R Markdown?

This question is similar to consistent code html inline and in chunks with knitr. Instead of .Rhtml documents, I want to highlight inline R code in R Markdown documents, e.g., after `r "plot(cars, main = 'A scatterplot.')"` is compiled through rmarkdown, the tokens like plot should be highlighted. By default, R code chunks are syntax highlighted, but there is no way to highlight inline R code.
Here is one solution using the development version of the highr package (devtools::install_github('yihui/highr')). Basically you just define your custom LaTeX commands to highlight the tokens. highr:::cmd_pandoc_latex is a data frame of LaTeX commands that Pandoc uses to do syntax highlighting.
head(highr:::cmd_pandoc_latex)
## cmd1 cmd2
## COMMENT \\CommentTok{ }
## FUNCTION \\NormalTok{ }
## IF \\NormalTok{ }
## ELSE \\NormalTok{ }
## WHILE \\NormalTok{ }
## FOR \\NormalTok{ }
Then you can redefine the inline hook of knitr:
---
output:
pdf_document:
keep_tex: yes
---
```{r include=FALSE}
local({
hi_pandoc = function(code) {
if (knitr:::pandoc_to() != 'latex') return(code)
if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required')
res = highr::hi_latex(code, markup = highr:::cmd_pandoc_latex)
sprintf('\\texttt{%s}', res)
}
hook_inline = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x)
})
})
```
Test inline R code: `r I("plot(cars, main = 'A scatterplot.')")`.
Normal inline code `r pi`.
A code block:
```r
plot(cars, main = 'A scatterplot.')
1 + 2 # a comment
```
I used I() as a convenient marker to tell the character strings to be syntax highlighted from normal character strings. It is just an arbitrary choice. PDF output:
This is not a perfect solution, though. You will need to tweak it in some cases. For example, most special LaTeX characters are not escaped, such as ~. You may need to process the LaTeX code returned by hi_pandoc() by gsub().
Personally I find multiple colors in inline output distracting, so I would not syntax highlighting it, but this is entirely personal taste.
Now-a-days:
Here is some `plot(cars, main = 'A scatterplot.')`{.R} inline R code
Well, I don't know specifically about R and the way you're using it, but for most languages (pandoc uses the skylighting pkg to do this), you can do inline code blocks with the above syntax.

How do I set conditional LaTeX code using R?

Suppose in my R/Sweave created LaTeX document, I want to have \subsection{Foo} if in my R code we have that x==1, whereas if x==2 in my R code I want \subsection{Bar} to be displayed.
How do I accomplish this? I know how to include R code by encapsulating it in <<>>= and # but I'm not sure how to do something such as the following (perhaps nonsensical) pseudo-code:
if(x==1)
Show \subsection{Foo} in LaTeX document
else if(x==2)
Show \subsection{Bar} in LaTeX document
What I also want to do that is very closely related is have subheading \subsection{z} in my LaTeX document, where z is defined strictly in my R code as some arbitrary string that I can toggle.
\Sexpr{} can evaluate expressions inline:
Show \subsection{\Sexpr{if(x==1) "Foo" else "Bar"}} in LaTeX document
\subsection*{\Sexpr{z}}
Use results=tex and cat the LaTeX code you want.
<<results=tex>>=
if(x==1) {
z <- "Foo"
} else if(x==2) {
z <- "Bar"
}
cat("\\subsection{", z, "}\n", sep="")
#

Sweave + RweaveHTML: cat output does not appear in the output

I have a problem with Sweave + RweaveHTML
I want the output of cat ends to up in the html file being generated. I have a case in which it does not and I can't figure out why :(
test = function()
{
#bla bla;
cat("Result is...")
}
And then in the Rnw file I tried all of these:
<<echo=FALSE, results=html, include=TRUE>>=
test()
#
<<results=html, include=TRUE>>=
test()
#
<<results=html>>=
test()
#
<<>>=
test()
#
But I don't get the cat output in the resulting HTML file.
I'm pretty sure this is supposed to work...
Any ideas of what I'm supposed to do to get the stdout ouput to the final html file?
Thx!
The RweaveHTML driver works differently than the RweaveLatex driver in that to create output, the result from every line of code is processed with the generic function HTML. Other ways of creating output don't work. So to get output from within a function, there are two ways I know of; one is to return a value to be processed by the HTML generic, and the other is to call HTML directly. The following replacement of your test function demonstrates both.
test <- function() {
#bla bla;
HTML("Result is...")
"Return value is"
}
It's also possible to replace cat with HTML; then your original function would work. But it's a bit of a hack and could have unforeseen consequences; you'd put
cat <- HTML
in a (probably hidden) Sweave chunk at the beginning of the document.

Resources