Conditionally output paragraph with inline R chunks - r

In my knitr repport I have several paragraphs that are only relevant if some criteria is met.
Wrapping everything in an inline r ifelse(... gets convuluted real fast.
So I tried with a code chunk like this
```{r conditional_block, eval=nrow(data)>0, results="asis"}
print("For theese `r nrow(data)` people, the mean salary is `r paste(round(mean(data$sallary),2))` dollars per year")
```
I tried with print, paste and cat. And I tired with results asis and markup. But the output is always - 'raw' the inline R code shows verbatim.

The problem with the code chunk shown in the question is rather conceptual than technical: The content of the chunk is interpreted as R code. Using knitr's syntax for inline output in the R context is neither possible nor necessary. Instead, the normal string functions should be used to compose the output string:
```{r conditional_block, eval=nrow(data)>0, results="asis"}
cat(sprintf(
"For these %d people, the mean salary is %.2f dollars per year.",
nrow(data), mean(data$salary))
)
```

Related

Rmd: Can I produce a new line within an R chunk that doesn't appear as R Comment in a Word Document?

do you have any solutions to producing a blank line within an Rchunk in Rmd? I want to put it out as a word document.
Currently I am doing this:
flextable(table1)
cat(" \n")
flextable(table2)
But this doesn't produce a line between the tables. If I do this instead:...
flextable(table1)
cat("Some Text")
flextable(table2)
... I get a line between the tables, but it's with a grey background and leading "## ".
I don't want to use seperate Rchunks, because I want to write a function that allows me to print multiple tables at once seperated by a blank space.
Do you have any ideas?
Kind regards
One way is to set the chunk option results='asis' such that
text output is written “as-is”, e.g., you can write out raw Markdown
text from R code
Xie, Yihui, Joseph J. Allaire, and Garrett Grolemund. R markdown: The definitive guide. Chapman and Hall/CRC, 2018.
and also make sure the output from cat is not in conflict with flextable output. Adding \n on each side of \\newline seems to work. We then have the chunk
```{r, echo=FALSE, results='asis'}
flextable(mtcars[1:4, ])
cat("\n \\newline \n")
flextable(mtcars[1:4, ])
```
results='asis' might come in conflict with some other stuff. If this is the case, you can omit this option and use knitr::asis_output() only at the desired output
```{r, echo=FALSE}
flextable(mtcars[1:4, ])
knitr::asis_output("\n \\newline \n")
flextable(mtcars[1:4, ])
```

R notebook: opts_chunk has no effect

I'm working on my first R notebook which works pretty well, except for one issue.
I'd like to be the numbers that I output inline with
`r realbignumber`
to have commas as separator and max 2 decimal points: 123,456,789.12
In order to achieve this, I added a chunk at the beginning of my document, which contains...
```{r setup}
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, cache = TRUE, message = FALSE)
knitr::opts_chunk$set(inline = function(x){if(!is.numeric(x)){x}else{prettyNum(round(x,1), big.mark = ",")}})
options(scipen=999)
```
The suppression of scientific numbers works like a charm, so the chunk is definitely executed. However, formatting of the inline output of numbers does not work.
Any ideas why that could be?
Do these kinds of settings generally not work with R notebooks?
Edit:
The solution suggested here also has no effect on the output format of numbers.
Here is an example illustrating two ways to print a large number in an R Markdown document. First, code to use the prettyNum() function in an inline R chunk.
Sample document where we test printing a large number. First set the number in an R chunk.
```{r initializeData}
theNum <- 1234567891011.03
options(scipen=999,digits=16)
```
The R code we'll use to format the number is: `prettyNum(theNum,width=23,big.mark=",")`.
Next, print the large number. `r prettyNum(theNum,width=23,big.mark=",")`.
The alternative of using chunk options works as follows.
Now, try an alternative using knitr chunks.
```{r prettyNumHook }
knitr::knit_hooks$set(inline = function(x) { if(!is.numeric(x)){ x }else{ prettyNum(x, big.mark=",",width=23) } })
```
Next, print the large number by simply referencing the number in an inline chunk as `theNum`: `r theNum`.
When both chunks of code are embedded in an Rmd file and knit, the output is as follows, showing that both techniques produce the same result.
regards,
Len

R Markdown makes custom plot disappear if I set echo=FALSE

I created a custom function which sets mfrow to nxn and creates n^2 scatter plots, with multiple data sets on each plot, based on an input list of data frames. The signature of my plotting function looks like this:
plot.return.list<-function(df.list,num.plot,title)
Where df.list is my list of data frames, num.plot is the total number of plots to generate (used to set mfrow) and title is the overall plot title (the function generates titles for each individual sub-graph).
This creats plots fine when I run the function from the console. However, I'm trying to get this figure into a markdown document using RStudio, like so:
```{r, fig.height=6,fig.width=6}
plot.return.list(f.1.list,4,bquote(atop("Numerical Approximations vs Exact Soltuions for "
,dot(x)==-1*x*(t))))
```
Since I haven't set the echo option in my {r} statement, this prints both the plotting code as well as the plot itself. However, if my first line instead reads:
{r, fig.height=6,fig.width=6,echo=FALSE}
Then both the code AND the plot disappear from the final document.
How do I make the plot appear WITHOUT the code? According to the example RStudio gives, setting echo=FALSE should make the plot appear without the code, but that isn't the behavior I'm observing.
EDIT: I seem to have tracked my problem down to kable. Whether or not I'm making a custom plot-helper function, any call to kable kills my plot. This can be reproduced in a markdown:
---
title: "repro"
author: "Frank Moore-Clingenpeel"
date: "October 9, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
options(default=TRUE)
repro.df<-data.frame((0.1*1:10)%*%t(1:10))
```
```{r, echo=FALSE}
kable(repro.df)
```
```{r, fig.height=6,fig.width=6,echo=FALSE}
plot(repro.df[,1],repro.df[,2])
```
In this code, the plot won't plot because I have echo set to false; removing the flag makes the plot visible
Also note that in my repro code, kable produces a table with a bunch of garbage in the last line--I don't know why, but this isn't true for my full original code, and I don't think it's related to my problem.
Thanks for the reproducible example. From this I can see that the problem is you don't have a newline between your table chunk and your plot chunk.
If you were to knit this and examine the MD file produced by knit (or set html_document as your output format and have keep_md: true to look at it), you would see that the table code and plot code are not separated by any newline. Pandoc needs this to delimit the end of the table. Without it, it thinks your ![](path/to/image.png) is part of the table and hence puts it as a "junk line" in the table rather than an image on its own.
Just add a newline between the two chunks and you will be fine. (Tables need to be surrounded with blank lines).
(I know you are compiling to LaTeX so it may confuse you why I am talking about markdown. In case it does, when you do Rmd -> PDF, Rmarkdown uses knit to go from RMD to MD, and then pandoc to go from MD to tex. This is why you still need to make sure your markdown looks OK).

How do I present a variable out of sequence in R markdown?

I am preparing a .Rmd document that begins with an executive summary. I would like to include some inline R code to present a few of the key results up front; however, those results are calculated as part of the body later in the document.
Is there any way to present a result in the rendered document out of order/sequence with the actual calculation?
You could use chunk reuse in knitr (see http://yihui.name/knitr/demo/reference/). Here you would put your chunks to analyze first but not create the output, then output the summary, then the details. Here is some quick markdown knitr code to show this:
```{r chunk1, echo=FALSE, results='hide'}
x <- rnorm(1)
x
```
the value of x is `r x`.
```{r chunk2, ref.label='chunk1', echo=TRUE, results='markup', eval=2}
```
Note that the code will be evaluated twice unless you take steps to prevent this (the eval=2 in my example).
Another option would be to create 2 child documents, the first runs your main code and creates the output, the second creates the summary. Then in your parent document you include the summary first, then the detail part. I think that you will need to run knitr on these by hand so that you do it in the correct order, the automatic child document tools would probably run in the wrong order.

Is there a way to prevent line break in the HTML when results='hide' and echo=FALSE?

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

Resources