R flextable - 如何在合并单元格下添加 table 宽的水平边框

R flextable - How to add a table-wide horizontal border under a merged cell

合并单元格时,是否有聪明的方法让水平边框 table 变宽? (在下面的示例中,它还不是 table 宽)。

或者我应该写一个函数来计算正确的索引吗?

library(flextable)
library(officer)
library(dplyr)

myft <- flextable(head(mtcars), 
                  col_keys = c("am", "carb", "gear", "mpg", "drat" ))%>% 
  theme_vanilla()%>%
  merge_v(j = c("am"))%>%border(border.bottom = fp_border(style = "solid", width=2), i=c(3,6), part="body")

myft

这是您想要的代码。它需要做更多的工作才能通用 - 该示例仅在第 1 列是唯一具有合并单元格的情况下才适用。

library(flextable)
library(officer)
library(dplyr)

bigborder <- fp_border(style = "solid", width=2)
myft <- flextable(head(mtcars), 
                  col_keys = c("am", "carb", "gear", "mpg", "drat" ))%>% 
  theme_vanilla()%>%
  merge_v(j = c("am")) 

# here starts the trick
row_loc <- rle(cumsum( myft$body$spans$columns[,1] ))$values
myft <- myft %>% 
  border(border.bottom = bigborder, i=row_loc, j = 2:5, part="body") 
myft <- myft %>% 
  border(border.bottom = bigborder, 
         i = myft$body$spans$columns[,1] > 1, j = 1, part="body") %>% 


  border(border.bottom = bigborder, border.top = bigborder, part = "header")
myft

一个更简单的解决方案是添加一个列来指示哪些行需要底部边框,然后添加一个 hline() 以及使用该值的行选择。通过使用 col_keys.

仅选择要在原始 flextable 规范中显示的列,可以将辅助选择排除在 table 之外
library(tidyverse)
library(flextable)

your_flextable = tibble(
  col_group = rep(letters[1:3], each = 3),
  the_value = rnorm(length(col_group))
) %>%
  group_by(col_group) %>%
  mutate(
    is_last_val_in_group = row_number() == max(row_number())
  ) %>%
  flextable(col_keys = c('col_group', 'the_value')) %>%
  merge_v(j = 'col_group') %>%
  hline(i = ~is_last_val_in_group == TRUE, border = fp_border()) %>%
  fix_border_issues()