---
title: |
  Introducción a

  la Minería de texto

  con ayuda de R
#Quarto Academic Typst  
subtitle: A Minimalistic Quarto + Typst Template for Academic Writing
#header: Please click [HERE](https://kazuyanagimoto.com/quarto-academic-typst/template-full.pdf) for the latest version.
author: "Kazuharu Yanagimoto"
    #- name: Kazuharu Yanagimoto
    #email: kazuharu.yanagimoto@cemfi.edu.es
    #orcid: 0009-0007-1967-8304
    #affiliations:
    #  - name: CEMFI
abstract: |
  {{< lipsum 1 >}}
resumen: |
  Este trabajo presenta una metodología de optimización para la toma de decisiones en el diseño y fabricación de un monoplaza de competición. Se desarrollan algoritmos de optimización multiobjetivo que consideran aspectos aerodinámicos, estructurales y de rendimiento del vehículo.

  La investigación se centra en la aplicación de técnicas de optimización avanzadas para equilibrar los diferentes objetivos conflictivos presentes en el diseño de vehículos de competición, como la minimización del peso, la maximización de la eficiencia aerodinámica y la optimización de la distribución de fuerzas.

  Los resultados obtenidos muestran mejoras significativas en el rendimiento global del vehículo, validadas mediante simulaciones computacionales y pruebas experimentales.
    
agradecimientos: |
  {{< lipsum 1 >}}
palabras-clave: [Quarto, Typst, formato]  
keywords: [Quarto, Typst, format]
date: today
date-format: full
lang: es
bibliography: testfull/references.bib

format:
  memoriatfetypst-typst:
    section-numbering: "1.1.1"
    toc: true
    bibliographystyle: "chicago-author-date"
    #bibliographystyle: "apa"
    bibliografia-completa: "true"
    keep-typ: true    
    cabecera-capitulo: "estilo01"
    #nombre-capitulo: "Capítulo"
    referencias-nombre: "Bibliografía"
    apendice-nombre: "Anexo"
    apendice-portada: "Anexos"
    fontsize: 10pt
    totablas: "true"
    tofiguras: "true"
    toccapitulos: "false"
    titulacion: "Doble Grado en Matemáticas y Estadística"
    tutor-TFG: "Tutor: Pedro L. Luque"
    facultad: "Facultad de Matemáticas"
    universidad: "Universidad de Sevilla"
    margin: 
      x: 2cm 
      y: 2cm
    fecha-TFG: "Sevilla, Junio de 2024"
  html:
    toc: true
brand: 
  typography:
    fonts:
      - family: Jost
        source: google
        weight: [100, 200, 300, 400, 500, 600, 700, 800, 900]
      - family: Libertinus Serif
        source: file
        files:
          - path: static/fonts/Libertinus-7.051/static/OTF/LibertinusSerif-Regular.otf
          - path: static/fonts/Libertinus-7.051/static/OTF/LibertinusSerif-Italic.otf
            style: italic
      - family: Libertinus Math
        source: file
        files:
          - path: static/fonts/Libertinus-7.051/static/OTF/LibertinusMath-Regular.otf
    base: Libertinus Serif
    #headings: Jost
  defaults:
    memoriatfetypst-typst:
      mathfont: Libertinus Math
execute: 
  echo: false
  warning: false
---

<!-- This document shows a practical usage of the template.
I use the Palmer penguins dataset [@horst2020] to demonstrate the features of the template.
The code is available [here](https://kazuyanagimoto.com/quarto-academic-typst/template-full.qmd). -->

```{r}
#| label: setup
library(dplyr)
library(ggplot2)
library(patchwork)
library(tinytable)
library(modelsummary)
library(showtext)
library(palmerpenguins)

color_accent <- "#107895"
color_accent2 <- "#9a2515"
color_accent3 <- "#e64173"

font_base_regular <- "Roboto Condensed"
font_base_light <- "Roboto Condensed Light"

# font_add_google(font_base_regular, font_base_light)
showtext_auto()

theme_quarto <- function(
  font_title = font_base_regular,
  font_text = font_base_light,
  size_base = 11
) {
  ggplot2::theme_minimal(base_family = font_text, base_size = size_base) +
    ggplot2::theme(
      plot.title = ggplot2::element_text(
        size = size_base * 1.2,
        face = "bold",
        family = font_title
      ),
      plot.subtitle = ggplot2::element_text(
        size = size_base,
        face = "plain",
        family = font_text
      ),
      plot.caption = ggplot2::element_text(
        size = size_base * 0.6,
        color = "grey50",
        face = "plain",
        family = font_text,
        margin = ggplot2::margin(t = 10)
      ),
      panel.grid.minor = ggplot2::element_blank(),
      strip.text = ggplot2::element_text(
        size = size_base * 0.9,
        hjust = 0,
        family = font_text,
        face = "bold"
      ),
      strip.background = ggplot2::element_rect(
        fill = "#ffffff",
        color = NA
      ),
      axis.ticks = ggplot2::element_blank(),
      axis.title = ggplot2::element_text(
        family = font_text,
        face = "plain",
        size = size_base * 0.8
      ),
      axis.title.x = ggplot2::element_text(
        margin = ggplot2::margin(t = 5)
      ),
      axis.text = ggplot2::element_text(
        family = font_text,
        face = "plain"
      ),
      legend.title = ggplot2::element_blank(),
      legend.key = ggplot2::element_blank(),
      legend.text = ggplot2::element_text(
        size = size_base * 0.75,
        family = font_text,
        face = "plain"
      ),
      legend.spacing = ggplot2::unit(0.1, "lines"),
      legend.box.margin = ggplot2::margin(t = -0.5, unit = "lines"),
      legend.margin = ggplot2::margin(t = 0),
      legend.position = "bottom",
      plot.title.position = "plot"
    )
}
```

# Section as Heading Level 1

Section numbering can be specified in the YAML `section-numbering` field
as other Typst templates.

## Subsection as Heading Level 2

You can use LaTeX math expressions:

$$
Y_{it} = \alpha_i + \lambda_t + \sum_{k \neq -1} \tau_h \mathbb{1}\{E_i + k = t\} +
\varepsilon_{it}.
$$

I choose a mathematical font which supports the indicator function $\mathbb{1}\{\cdot\}$.
Currently, I use the Libertinus Math font.

### Subsubsection as Heading Level 3

I don't use and don't recommend using heading levels 3 and below but it works.

## Citation

You can cite a reference like this [@katsushika1831] or @horst2020.
Typst has some built-in citation styles. Check the [Typst documentation](https://typst.app/docs/reference/model/bibliography/#parameters-style) for more information.

# Figures and Tables

## Figures

As @fig-facet shows, the caption is displayed below the figure.
As a caption of the figure (`fig-cap`), I use bold text for the title and use a normal text for the description.

```{r}
#| fig-width: 6
#| fig-height: 3
#| label: fig-facet
#| fig-cap: |
#|   **Flipper Length and Bill Length of Penguins**.
#|   The x-axis shows the flipper length, and the y-axis shows the bill length.

penguins |>
  filter(!is.na(sex)) |>
  mutate(
    lbl_facet = recode_factor(sex, `male` = "Male", `female` = "Female")
  ) |>
  ggplot(aes(
    x = flipper_length_mm,
    y = bill_length_mm,
    color = species,
    shape = species
  )) +
  geom_point(size = 2) +
  geom_smooth(method = "lm", se = FALSE) +
  scale_color_manual(values = c(color_accent, color_accent2, color_accent3)) +
  facet_wrap(~lbl_facet) +
  labs(x = "Flipper Length (mm)", y = "Bill Length (mm)") +
  theme_quarto() +
  theme(legend.position = c(0.9, 0.1))
```

When I want to show multiple figures side by side, I use the `patchwork` package.
The reason why I don't use the `layout-col` option is that the caption is also split into two parts.

```{r}
#| fig-width: 6
#| fig-height: 3
#| label: fig-patchwork
#| fig-cap: |
#|  **Characteristics of Penguins**.
#|  The left panel shows the relationship between flipper length and body mass.
#|  The right panel shows the density of flipper length.

p1 <- penguins |>
  ggplot(aes(
    x = flipper_length_mm,
    y = body_mass_g,
    color = species,
    shape = species
  )) +
  geom_point(size = 2) +
  scale_color_manual(values = c(color_accent, color_accent2, color_accent3)) +
  labs(x = "Flipper Length (mm)", y = "Body Mass (g)") +
  theme_quarto() +
  theme(legend.position = c(0.9, 0.1))

p2 <- penguins |>
  ggplot(aes(x = flipper_length_mm, color = species, shape = species)) +
  geom_density() +
  scale_color_manual(values = c(color_accent, color_accent2, color_accent3)) +
  labs(x = "Flipper Length (mm)", y = "Density") +
  theme_quarto() +
  theme(legend.position = c(0.9, 0.1), panel.grid.major.x = element_blank())

p1 + p2
```


## Tables

You can use [tinytable](https://vincentarelbundock.github.io/tinytable/)
for general tables and [modelsummary](https://vincentarelbundock.github.io/modelsummary/) for regression tables.
As @tbl-sum-penguins shows, the caption is displayed above the table.
The notes of the table can be added using the `notes` argument of the `tinytable::tt()` function.

```{r}
#| label: tbl-sum-penguins
#| tbl-cap: Summary Statistics of Penguins

penguins |>
  filter(!is.na(sex)) |>
  summarize(
    across(bill_length_mm:body_mass_g, ~ mean(.x, na.rm = TRUE)),
    .by = c(species, sex)
  ) |>
  tidyr::pivot_wider(
    names_from = sex,
    values_from = c(
      bill_length_mm,
      bill_depth_mm,
      flipper_length_mm,
      body_mass_g
    )
  ) |>
  select(species, ends_with("_male"), ends_with("_female")) |>
  `colnames<-`(c(
    "",
    rep(
      c(
        "Bill Length (mm)",
        "Bill Depth (mm)",
        "Flipper Length (mm)",
        "Body Mass (g)"
      ),
      times = 4
    )
  )) |>
  tt(notes = "Notes: Data from Palmer penguins dataset.") |>
  group_tt(j = list("Male" = 2:5, "Female" = 6:9)) |>
  format_tt(j = c(2:9), digits = 4)
```

Since the default backend of `modelsummary` is `tinytable`,
you can use the customization options of `tinytable` for `modelsummary`.
In @tbl-regression, I use `tinytable::group_tt()` function to group the regression results by the dependent variables

```{r}
#| label: tbl-regression
#| tbl-cap: Regression Results of Penguins
cm <- c(
  "speciesChinstrap" = "Chinstrap",
  "speciesGentoo" = "Gentoo",
  "sexmale" = "Male",
  "year" = "Year"
)

gm <- tibble(
  raw = c("nobs", "r2"),
  clean = c("Observations", "$R^2$"),
  fmt = c(0, 3)
)

list(
  "(1)" = lm(bill_length_mm ~ species, data = penguins),
  "(2)" = lm(bill_length_mm ~ species + sex, data = penguins),
  "(3)" = lm(bill_length_mm ~ species + sex + year, data = penguins),
  "(4)" = lm(body_mass_g ~ species, data = penguins),
  "(5)" = lm(body_mass_g ~ species + sex, data = penguins),
  "(6)" = lm(body_mass_g ~ species + sex + year, data = penguins)
) |>
  modelsummary(
    stars = c("+" = .1, "*" = .05, "**" = .01),
    coef_map = cm,
    gof_map = gm,
    notes = "Notes: Data from Palmer penguins dataset."
  ) |>
  group_tt(j = list("Bill Length (mm)" = 2:4, "Body Mass (g)" = 5:7))
```

While `tinytable` generates compatible tables between LaTeX and Typst,
it does not support LaTeX math expressions for Typst tables.
I think the compatibility between LaTeX and Typst is crucial for academic writing
because it guarantees that the document can be easily converted to LaTeX for submission to journals.

A workaround is to use [MiTeX](https://typst.app/universe/package/mitex/),
a Typst package that allows you to use LaTeX math expressions in Typst.
I write a custom theme for `tinytable` to convert LaTeX math expressions to MiTeX expressions.
The following table includes LaTeX math expressions but will be converted to MiTeX expressions in the Typst output.

Ver más en: <https://github.com/kazuyanagimoto/quarto-academic-typst/blob/main/template-full.qmd>{target="_blank"}


# Last words

I made this template for my working papers, so it may not be suitable for other fields than economics.
I am happy to receive feedback and suggestions for improvement.



```{r}
#| child: "testfull/capitulo01.qmd"
#| echo: false
```

```{r}
#| child: "testfull/capitulo02.qmd"
#| echo: false
```

```{r}
#| child: "testfull/capitulo03.qmd"
#| echo: false
```



{{< appendix >}}

# Supplemental Figures 

The section numbering will be changed to "A.1.1" in the appendix.
The second section in the appendix will be "B".
On the other hand, the figure numbering will be reset to "A.1", "A.2"
so that it is clear that these figures are part of the appendix.
The "A" stands for the "Appendix", not the section numbering.

![**The Great Wave off Kanagawa**. A woodblock print by @katsushika1831.](img/hokusai_kanagawa.jpg){#fig-img width=80%}

# Otro apéndice

The section numbering will be changed to "A.1.1" in the appendix.
The second section in the appendix will be "B".
On the other hand, the figure numbering will be reset to "A.1", "A.2"

{{< lipsum 1 >}}

## Apartado de ejemplo

{{< lipsum 3 >}}

## Otro apartado de ejemplo

{{< lipsum 8 >}}

## Otro 3 apartado de ejemplo

{{< lipsum 8 >}}



```{r}
#| child: "testfull/apendice03.qmd"
#| echo: false
```



{{< pagebreak >}}
<!-- Bibliography -->
