How do I set conditional LaTeX code using R? - 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="")
#

Related

If else in R Markdown, colored text

I have a R Markdown child-file, which should produce different output based on a R-condition .
My code (sorry it is not reproducible):
{r results='asis', echo = FALSE}
if (class(robject) == "character") {
cat("**R object is empty!**") # This text should appear in RED in the Output (HTML) file.
} else {
cat("### Data columns\n")
cat("\n")
kable(robject)
cat("\n")
}
What the code does:
If my robject is not a data.frame it is set to an empty string (robject <- ""). With this "trick" it is possible to if_else about robject.
In my R Markdown file it should be printed either "R object is empty!" or a summary of the dataset (which is a data.frame again). If the dataset is empty, the text should appear in RED!
Two questions:
How to print the text in RED (or every other color) using the cat command as in the example above?
(I tried text_spec from kableextra as mentioned here, I tried crayron-Package as well and I tried to enter html_tags with print/cat . Neither worked!)
Maybe it is better to if else outside the R Chunk. Unfortunately this approach did not work either enter link description here
Thank you for any help.
If you need some further information, please ask me for it. Thanks!
For HTML you can wrap the text in <span> and use CSS to set the color. If you need to do this more than a couple of times, you can wrap it up in a simple function.
```{r results='asis', echo = FALSE}
cat_color <- function(message, color = "black") cat(sprintf("<span style = \"color: %s;\">%s</span>\n\n", color, message))
robject <- "some text"
if (class(robject) == "character") {
cat_color("**R object is empty!**" , "red") # This text should appear in RED in the Output (HTML) file.
} else {
cat("### Data columns\n")
cat("\n")
kable(robject)
cat("\n")
}
```

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.

Inline knitr print code not printing

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.

Latex inside r code chunk?

Is it possible to insert a LaTeX code in a r code chunk?
I'm printing tables in a loop (using results='asis'option, I know I can use print to display some text, but ideally I would love each table to be in a separate \subsection, or at least to display comments with nicely formatted formulas.
...
\section{Section}
<<echo=FALSE, results="asis">>=
for (i in 1:3) {
# here I want to insert a subsection with a title contating for instance x^i
plot(i:(i*10), col=i)
}
#
...
Anyone struggling with this also?
Thanks to #Benjamin's and #Ben Bolker's comments I now know the answer:
...
\section{Section}
<<echo=FALSE, results="asis">>=
for (i in 1:3) {
cat('\\subsection{$x^', i, '$}')
plot(i:(i*10), col=i)
}
#
\end{document}
...

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