Created
October 8, 2026 18:00
-
-
Save graebnerc/ceed67c7a3835ce3aaedb78c099417fe to your computer and use it in GitHub Desktop.
Inline R code and table cells
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- | |
| title: "Inline R code: referencing a table cell" | |
| format: html | |
| --- | |
| ```{r} | |
| #| label: setup | |
| #| message: false | |
| library(tidyverse) | |
| library(flextable) | |
| gdp <- tibble( | |
| country = c("Germany", "France", "Denmark"), | |
| year = c(2023, 2023, 2023), | |
| gdp_pc = c(52745.8, 44460.2, 67967.4) | |
| ) | |
| ``` | |
| ```{r} | |
| #| label: tbl-gdp | |
| #| tbl-cap: "GDP per capita (USD)" | |
| flextable(gdp) |> | |
| autofit() | |
| ``` | |
| ## Referencing a single cell in the text | |
| GDP per capita in France was `r gdp |> filter(country == "France") |> pull(gdp_pc)` USD. | |
| Formatted with a thousands separator and no decimals: | |
| `r gdp |> filter(country == "Germany") |> pull(gdp_pc) |> scales::comma()` USD. | |
| ## Better: compute in a hidden chunk, reference in the text | |
| ```{r} | |
| #| include: false | |
| top <- gdp |> slice_max(gdp_pc, n = 1) | |
| top_country <- top |> pull(country) | |
| top_value <- top |> pull(gdp_pc) |> scales::comma() | |
| ``` | |
| The richest country in @tbl-gdp is `r top_country` with `r top_value` USD. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment