jhelvy
jhelvy

Reputation: 687

Is it possible to put an RMarkdown chunk inside a table cell in a Rmd file?

I want to create a table inside a RMarkdown document that has a code chunk inside one of the table cells. I can put inline code using the `` symbols inside a table cell, but not an entire, multi-line code chunk.

For example, in-line code works fine to produce a markdown table:

header1 | header2
--------|--------
`code`  | text

But what if you want to put a code chunk in the lower-left corner instead of inline code? Say for example you have the following chunk and you want it in one of the table cells:

```{r}
2 + 2
3 + 3
```

I have no idea how to achieve this.

Edit: The html solutions provided by yifan are great! But, what about for pdf outputs? We discussed this in this issue on the rmarkdown github page. Best solution for now seems to be to use grid tables, like this:

+----+-----+
|col1|col2 |
+====+=====+
|``` |foo  |
|a   |     |
|b   |     |
|``` |     |
+----+-----+

This will work for code blocks, but not code chunks, which does not seem feasible without substantial changes to rmarkdown or knitr.

Upvotes: 6

Views: 1043

Answers (1)

Yifu Yan
Yifu Yan

Reputation: 6106

Method 1: Bootstrap table in HTML

<table class='table'>
<tr> <th>column1</th> <th>column2</th> <tr>
<tr>
<td>
```{r}
print("a")
```
</td>
<td>
```{r}
a = runif(10)
print(a)
```
</td>
<tr>
</table>

enter image description here

Method 2: Bootstrap Grids

<div class="container">
<div class="row">
<div class="col-md-6">Column 1</div>
<div class="col-md-6">Column 2</div>
</div>
<div class="row">
<div class="col-md-6">
```{r}
print("a")
```
</div>
<div class="col-md-6">
```{r}
a = runif(10)
print(a)
```
</div>
</div>
</div>

enter image description here

Upvotes: 3

Related Questions