-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reprex.qmd
104 lines (79 loc) · 2.64 KB
/
Reprex.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
---
title: "Dynamic Table Captions"
author: "Jon Peake"
format: html
editor: visual
---
## Example 1: from a column value
If the information for our dynamic caption is contained within a column in the dataset (say, a single static column for the species or gear), we can extract the information from the columns of interest. Let's create a dataset with a constant species and gear.
```{r}
#| label: createdata_colval
# Create a dummy dataset
dat <- data.frame(species = rep('Mycteroperca microlepis', 10),
gear = rep('Hook and line',10),
age = 1:10,
size = seq(1,100,10))
write.csv(dat, file = 'dat_colval.csv',row.names = F)
```
We can make a dynamic label in a few ways. If a caption with a similar format is going to be used multiple times throughout the document, it might be easiest to make this a function. Otherwise, we can just use a standard call to `paste`:
```{r}
# Make dynamic label
# read in the data file
dat <- read.csv('dat_colval.csv')
# extract the species name
spp <- unique(dat$species)
# extract the gear
gear <- unique(dat$gear)
# paste together the caption
cap <- paste('Age and length of',
spp,
'from',
gear)
cap
```
We can assign the caption using the `#| tbl-cap` option in our table code chunk. To input an r variable, we use the following notation:
```
#| tbl-cap: !expr cap
```
By using `!expr` we can insert an R variable or even a full expression into the caption. This example inserts the value of `cap` into the caption.
```{r}
#| label: tbl-colval
#| tbl-cap: !expr cap
# Make table using kable
library(knitr)
kable(dat)
```
## Example 2: from a column header
If instead our dynamic information is in a column header, we can use the `colnames` function to extract the appropriate information. This may be useful if the structure of the data is constant but a value column changes names across datasets.
```{r}
#| label: createdata_colname
# Create a dummy dataset
dat <- data.frame(species = rep('Mycteroperca microlepis', 10),
SL = 1:10,
FL = 1:10)
write.csv(dat, file = 'dat_colname.csv',row.names = F)
```
```{r}
# Make dynamic label
# read in the data file
dat <- read.csv('dat_colname.csv')
# extract the species name
spp <- unique(dat$species)
# extract the length types
param_1 <- colnames(dat)[2]
param_2 <- colnames(dat)[3]
# paste together the caption
cap <- paste(spp,
param_1,
'vs.',
param_2
)
cap
```
```{r}
#| label: fig-colname
#| fig-cap: !expr cap
# Make plot using ggplot
library(ggplot2)
ggplot(dat) + geom_point(aes(x = SL, y = FL))
```