Red Dog
Red Dog

Reputation: 3

Create a stacked 2 x 2 kable table in R with different dimension dataframes

I am trying to create in R a set of tables that can be in either html or latex or pdf form so I'm using kable. I want to create a 2 row and 2 column table with each cell containing information from a different dataframe. I want headers above each of the cells with different information. The tricky part for me is the tables have different so I want the cells to be as wide or long as a I specify and this would just add to the width and height of the overall table.

Basically i want it to look like this

enter image description here

I have this code so far

library(kableExtra)
df1 <- head(mtcars)
df2 <- head(iris)
df3 <- head(ChickWeight)
df4 <- head(airquality)

table1 <- kable(df1, format = "html") %>%
  kable_styling()
table2 <- kable(df2, format = "html") %>%
  kable_styling()
table3 <- kable(df3, format = "html") %>%
  kable_styling()
table4 <- kable(df4, format = "html") %>%
  kable_styling()


combined_table=kable(list(df1,df2, df3,df4), format="html") %>% 
  kable_styling() %>% 
  column_spec(column=1:4, border_left = T, border_right = T)

but I cannot rbind the dataframes when they have different column lengths. So how do I get them into different panels.

I included my code and expected it to panel the objects but it does not.

Upvotes: 0

Views: 220

Answers (1)

Julian
Julian

Reputation: 9310

Here is a way using the grid layout in quarto:

---
format: html
execute: 
  echo: false
---


```{r}
library(kableExtra)
df1 <- head(mtcars)
df2 <- head(iris)
df3 <- head(ChickWeight)
df4 <- head(airquality)

table1 <- kable(df1, format = "html") %>%
  kable_styling()
table2 <- kable(df2, format = "html") %>%
  kable_styling()
table3 <- kable(df3, format = "html") %>%
  kable_styling()
table4 <- kable(df4, format = "html") %>%
  kable_styling()
```

::: {.grid}

::: {.g-col-6}

## Combined Table
```{r}
table1
```

:::
  
::: {.g-col-6}
## {}
```{r}
table2
```

:::
  
:::  

::: {.grid}

::: {.g-col-6}

```{r}
table3
```

:::
  
::: {.g-col-6}

```{r}
table4
```

:::
  
:::  

enter image description here

Upvotes: 0

Related Questions