Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a 'hand-made' table using bookdown package

I'm trying to reference a table using the bookdown package. In the documentation for tables, the author only shows how to create tables using knitr::kable.

```{r table1}
knitr::kable(
  head(iris, 20), caption = 'Here is a nice table!',
  booktabs = TRUE
)
```

Table \@ref(tab:table1) is here.

Using knitr::kable works just fine. The caption of the table is displayed and I can reference the table. I would like to do the same with a classic, hand-made markdown table, but obviously the code below fails. What can I do to get a similar result as with the code above?

```{r table2, echo=FALSE, results='asis'}
cat('| Sepal.Length| Sepal.Width| Petal.Length|
|------------:|-----------:|------------:|
|          5.1|         3.5|          1.4|
|          4.9|         3.0|          1.4|
|          4.7|         3.2|          1.3|
|          4.6|         3.1|          1.5|')
```

Table \@ref(tab:table2) is here.

This picture shows the output of this code when it is knitted.

This

like image 744
nhoeft Avatar asked Apr 19 '16 15:04

nhoeft


2 Answers

I did mention it in the documentation, but perhaps it is not clear enough. I said you need the label of the form (\#tab:...). For example, you may refer to this table using \@ref(tab:foo).

Table: (\#tab:foo) Your table caption.

| Sepal.Length| Sepal.Width| Petal.Length|
|------------:|-----------:|------------:|
|          5.1|         3.5|          1.4|
|          4.9|         3.0|          1.4|
|          4.7|         3.2|          1.3|
|          4.6|         3.1|          1.5|
like image 157
Yihui Xie Avatar answered Nov 04 '22 21:11

Yihui Xie


I am joining the discussion a bit late, but I just wanted to share a working MWE (based on the earlier answers):

```{r , echo=FALSE, results='asis'}
  cat(' Table: (\\#tab:mwe) Example

  | Sepal.Length| Sepal.Width| Petal.Length|
  |------------:|-----------:|------------:|
  |          5.1|         3.5|          1.4|
  |          4.9|         3.0|          1.4|
  |          4.7|         3.2|          1.3|
  |          4.6|         3.1|          1.5|')

```

Table @ref(tab:table2) shows...

like image 40
Hans Henrik Sievertsen Avatar answered Nov 04 '22 22:11

Hans Henrik Sievertsen