Search code examples
rlatexr-markdown

Conditional textline avoiding a whiteline when no text is printed


I'm writing a script that creates custom pdf-reports for a few hundred teams. Based on the data per team the code chooses what advice and how many pieces of advice to print in the PDF-file for this specific team. I'm able to print different advice per team, or print no advice if there is none, but I fail to prevent him printing the line-end.

The code below will only print the header and advice when it is relevant, but it will always print a empty lines.

When 6 is not relevant this line should be directly followed by the fourth line of this example  
### `r if(params$df$relevant[6]){params$df$Heading[6]}`
`r if(params$df$relevant[6]){params$df$Advice[6]}`
When 6 is not relevant this line should directly below the first line of this example, without white lines in between

In my workflow I start in R which imports and analyses data for all teams. Per team it calls rmarkdown::render() to open a template .RMD/RMarkdown file, sending the advice text in a df via the parameters from the R-script to the template.

A brief description of other strategies I tried and failed with (and which would warrant a new question if the current one is a dead end?):

  • pre-format the text in R. That looks good in R, but the formatting gets ignored when printed to PDF by Rmarkdown. So I don't get line ends between the advices I do want to print
  • print the text within an R-code chunk. That will print the correct text, but I cannot get the R-code chunk to use the same font as the rest of the document.
  • use the ifelse() function instead. That doesn't seem to create a Header if you type ### in front of the row
    ...you can imagine my shame for being stumped by an if-statement...

I'm new to this forum. Please let me know if I can phrase the question more clearly without giving irrelevant info.


Solution

  • Welcome to SO!

    Not sure if there's a simpler approach but in similar situations I like to avoid markdown and inline R code and instead wrap it up in a code chunk (which also makes control flow easier):

    ```{r, results='asis', echo=F}
    a <- "When 6 is not relevant this line should be directly followed 
    by the fourth line of this example"
    b <- "When 6 is not relevant this line should directly below the 
    first line of this example, without white lines in between"
    
    if(params$params$df$relevant[6]) {
      cat(a, paste0('\\subsubsection{', params$df$Heading[6], '}'), b)
    } else {
      cat(a, "\\newline", b)
      }
    ```
    

    (\subsubsection and \newline are LaTeX commands for level-three heading and linebreak, respectively.)