Search code examples
rr-markdownrnotebook

How to set up font style and size for different sections of RMarkdown document?


Let see the following RMarkdown document.

How to set font types and sizes for these two sections, for example:

1 - "Arial, bold, 9pt" for the first section

2 - "Arial Narrow, bold, 8pt" for the second one.

Thanks!

---
title: "R Notebook"
output: pdf_document
---

## 1. First section with "First car name"

```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
# 1. Data
fist_car_name <- rownames(mtcars)[[1]]

# 2. Print name of the first car
cat(fist_car_name)
```

## 2. Second section with "Data about all cars"

```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(knitr)
library(kableExtra)

kable(mtcars)
```

Solution

  • We may use LaTeX code in Rmarkdown. \fontfamily for font family: phv is Helvetica and similar to Arial but doesn't need an extra package. \fontseries for font type: we use b for bold and bc for medium condensed (for other values see this tex.stackexchange answer). The font size we define with \small and \footnotesize which should correspond to 9pt and 8pt. To revert everthing we use \rmfamily\normalsize.

    ---
    title: "R Notebook"
    output: pdf_document
    ---
    ## 1. First section with "First car name"
    
    \fontfamily{phv}\fontseries{b}\small
    
    ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
    # 1. Data
    fist_car_name <- rownames(mtcars)[[1]]
    
    # 2. Print name of the first car
    cat(fist_car_name)
    ```
    
    ## 2. Second section with "Data about all cars"
    
    \fontfamily{phv}\fontseries{bc}\footnotesize
    
    ```{r echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
    library(knitr)
    library(kableExtra)
    
    kable(mtcars)
    ```
    ## 3. Let's switch back to defaults
    
    \rmfamily\normalsize
    
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod 
    tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
    

    Yielding

    enter image description here