kableExtra的第二列中具有add_indent()的行缩进

时间:2019-02-26 16:56:53

标签: r r-markdown kableextra

我尝试使用用于RMarkdown的kableExtra包缩进数据框第二列的单元格。看来add_indent()仅适用于第一列,因此在下面的reprex表中没有任何更改:

使用虚假数据代替:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(tidyverse)
library(kableExtra)


group <- c(1, NA, NA, 2, NA, NA)
quest <- c("How is your mood today?", "good or very good", "bad or very bad", 
           "What colour is your hair?", "brown", "other")
percent <- c(NA, 80, 20, NA, 50, 50)


df <- tibble(group, quest, percent)


```

## Reprex

```{r, echo=TRUE}
# output without add_indent()
kable(df, booktabs = T, escape = T) %>% 
  add_header_above(header = c("Group" = 1, 
                              "Question & answer options" = 1, 
                              " %Agreement" = 1)) %>% 
  gsub("NA", " ", .)
```


```{r with indent, echo=TRUE}
# output with add_indent()
kable(df, booktabs = T, escape = T) %>% 
  add_header_above(header = c("Group" = 1, 
                              "Question & answer options" = 1, 
                              " %Agreement" = 1)) %>% 
  gsub("NA", " ", .) %>% 
  add_indent(positions = c(2,3,5,6))

所需的输出:我想缩进第二列的第2、3、5、6行(答案选项应该位于问题下方,理想情况下也应位于斜体中)。斜体字也可以用cell_spec()覆盖,但是我认为这仅适用于列。

我想要的输出可能吗? (我想混合问题和答案选项没有意义,但是为了保持早期报告的格式,我们想尝试这种方式吗?)

1 个答案:

答案 0 :(得分:1)

这是两种可能的方式。

  1. 在另外的kableExtra::group_rows列中使用group条。

  2. 使用kableExtra手动添加缩进(1em添加cell_spec)。

选项1

```{r, echo = F}
df <- data.frame(quest, percent) 
df %>%
  mutate(quest = cell_spec(quest, italic = ifelse(row_number() %in% c(2,3,5,6), T, F))) %>%
  kable(booktabs = T, escape = F) %>%
  add_indent(c(c(2,3,5,6))) %>% 
  group_rows("Group 1", 1, 3) %>%
  group_rows("Group 2", 4, 6) %>%
  gsub("NA", " ", .)
```

## Option 2

```{r, echo = F}
df <- data.frame(group, quest, percent)
df %>%
  mutate(quest = cell_spec(quest, italic = ifelse(row_number() %in% c(2,3,5,6), T, F)),
         quest = ifelse(row_number() %in% c(2,3,5,6), paste0("\\hspace{1em}", quest), quest)) %>%
  kable(booktabs = T, escape = F) %>%
  gsub("NA", " ", .)
``` 

enter image description here