Rmarkdown: How to align static and dynamic text

Viewed 140

I have to combine static and dynamic text in an Rmarkdoen document that knits to PDF

an example is the following

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Testing

```{r echo=FALSE, include=FALSE}
df<-data.frame(let=c("a", "AAa", "BnhB", "jpoiölojk"), num=c(1, 23, 1, 9837))
```

**First line: `r df$let[1] ` `r df$num[1] `** \
**Second line:  `r df$let[2] ` `r df$num[2] `** \
**Third line: `r df$let[3] ` `r df$num[3] `**\
**Fourth line: `r df$let[4] ` `r df$num[4] `**

which knits to

enter image description here

which looks terrible.

I would to improve the alignment of the static and dynamic text as following

  1. All : should be below each other, the space between the last character of the previous word and the : should be filled with either .... or whitespace
  2. All df$let should start below each other aligned. Space should be filled with whitespace
  3. Similarly all df$num should start below each other aligned. Space should be filled with whitespace

As one sees let and num may have different lengths. I tried with spaces and &nbsp; but it does not seem to work. .

Is there any other way to make this aesthetically nicer? something like the Tab in Word processing?

Is maybe a table an option? However on the final PDF it must not look like a table, but like text

1 Answers

I would use a table. If you don't draw the lines, it will look like text

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Testing

```{r echo=FALSE, include=FALSE}
df<-data.frame(let=c("a", "AAa", "BnhB", "jpoiölojk"), num=c(1, 23, 1, 9837))
```

\begingroup
\bfseries%
\noindent%
\begin{tabular}{@{}lll@{}}
First line: & `r df$let[1] ` & `r df$num[1] `\\
Second line: & `r df$let[2] ` & `r df$num[2] `\\
Third line: & `r df$let[3] ` & `r df$num[3] `\\
Fourth line: & `r df$let[4] ` & `r df$num[4] `\\
\end{tabular}
\endgroup

enter image description here

Related