I am trying to create an HTML table using R and the kable and kableExtra packages. I am having problems creating a row that spans several columns. I want to create a table where the last row contains the same values for all the columns without actually repeating this value. I've created a small example of what I am trying to do below.
library(kableExtra)
library(knitr)
summary_stats <- matrix(c(51,43,22,22),ncol=2,byrow=TRUE)
colnames(summary_stats) <- c("Mean","SD")
rownames(summary_stats) <- c("Age","Observations")
summary_stats
kable_table <- kable(summary_stats) %>%
kable_styling()
Instead of repeating the number 22 on the last row for the two columns, I'd like to center it between the two columns.
I am able to achieve what I want with the following HTML code using the colspan argument:
<table class="table" style="margin-left: auto; margin-right: auto;">
<thead>
<tr>
<th style="text-align:left;"> </th>
<th style="text-align:right;"> Mean </th>
<th style="text-align:right;"> SD </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;"> Age </td>
<td style="text-align:right;"> 51 </td>
<td style="text-align:right;"> 43 </td>
</tr>
<tr>
<td style="text-align:left;"> Observations </td>
<td style="text-align:center;" colspan = "2"> 22 </td>
</tr>
</tbody>
</table>
Note that the HTML code is just the output of the kable_table object I created in R where I've manually edited the HTML code to include the colspan argument. I would like to do this programmatically within R instead of having to manually change the code.
I've tried to use the row_spec function from the kableExtra package to add the necessary code but I am limited by the fact that the add_css option (as expected) only accepts arguments related to styling. In other words, I cannot pass the colspan argument to the option.
My question is if there is a reasonable way of adding the necessary HTML to the table after I've created it or if there is any option within the kable/kabeExtra framework that allows me to do this that I've missed?