如何从数据帧列表中打印格式化(kable)表?

问题描述 投票:0回答:1

我有一个由数据帧组成的列表,我想在我的 Rmarkdown 文件上将每个列表元素打印为 knitr 表。但是,我需要在将每个数据帧上的单元格传递给 kable() 之前对其进行格式化。

基本上,我需要根据一个条件格式化每个数据帧中单元格的背景(如果单元格值为1,则为红色,如果为零则为白色),并将每个数据帧打印为表格(booktabs 样式)。

我使用以下代码,但表格未使用 booktabs 选项进行格式化:

library(tidyverse)
library(knitr)
library(kableExtra)


df1 <- data.frame("2016"=c(0,0,1,1), "2017"=c(1,1,1,1), "2018"=c(0,0,1,0), "2019"=c(1,0,0,0))
 
df2 <- data.frame("2016"=c(0,1,0,1), "2017"=c(1,0,0,1), "2018"=c(1,0,1,0), "2019"=c(1,0,1,1))
   

rownames(df1) <- c("sp1", "sp2", "sp3", "sp4")
rownames(df2) <- c("sp1", "sp2", "sp3", "sp4")

df.list <- list(df1,df2)

map(df.list, ~.x %>% mutate(across(everything(), ~cell_spec(., "html", background = ifelse(.x==1,  "red","white"), color = ifelse(.x==1, "red","white")))) %>% kable("html",  escape = F, booktabs = TRUE))

在我的块选项中,我有:

{r echo=FALSE, message=FALSE, warning=FALSE, eval=TRUE, results = "asis"}

似乎

kable
中的选项没有被评估...

有什么提示吗?

提前致谢:

佩德罗·内维斯

r list knitr kable
1个回答
0
投票

您似乎正在混合 html 和 LaTeX。

booktabs
参数适用于 LaTeX 输出。所以这可能就是您正在寻找的:

---
output: pdf_document
---

```{r include=FALSE}

library(dplyr)
library(purrr)
library(kableExtra)


df1 <- data.frame("2016"=c(0,0,1,1), "2017"=c(1,1,1,1), "2018"=c(0,0,1,0), "2019"=c(1,0,0,0))
 
df2 <- data.frame("2016"=c(0,1,0,1), "2017"=c(1,0,0,1), "2018"=c(1,0,1,0), "2019"=c(1,0,1,1))

rownames(df1) <- c("sp1", "sp2", "sp3", "sp4")
rownames(df2) <- c("sp1", "sp2", "sp3", "sp4")

df.list <- list(df1,df2)

```


   

```{r results='asis'}

map(df.list, ~.x |>  mutate(across(everything(), ~cell_spec(., "latex", background = ifelse(.x==1,  "red","white"), color = ifelse(.x==1, "red","white")))) |>  
      kbl(escape = FALSE,
            booktabs = TRUE))

```

输出如下:

© www.soinside.com 2019 - 2024. All rights reserved.