如何合并单元格在flextable多行标题在flextable在R?

x8diyxa7  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(140)

下面是我的flextable表:

library(flextable)
library(tidyverse)
library(officer)
library(magrittr)

M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))

dimnames(M) <- list(
  gender = c("F", "M"),
  party = c("Democrat", "Independent", "Republican"))

M
f <- ftable(M,
            row.vars = "gender",
            col.vars = c("party"))

ftable_to_flextable <- function( x ){

  row.vars = attr( x, "row.vars" )
  col.vars = attr( x, "col.vars" )
  rows <- rev( expand.grid( rev(row.vars), stringsAsFactors = FALSE ) )
  cols <- rev(expand.grid( rev(col.vars), stringsAsFactors = FALSE ))

  xmat <- as.matrix(x)
  cols$col_keys = dimnames(xmat)[[2]]
  xdata <- cbind(
    data.frame(rows, stringsAsFactors = FALSE),
    data.frame(xmat, stringsAsFactors = FALSE)
  )
  names(xdata) <- c(names(row.vars), cols$col_keys)

  ft <- flextable(xdata)
  ft <- set_header_df(ft, cols)
  ft <- theme_booktabs(ft)
  ft <- merge_v(ft, j = names(row.vars))
  ft
}


final <- ftable(M) %>% ftable_to_flextable()

ft_2 <- add_header_row(final, values = c("Party"), colwidths = c(4), top = TRUE)

ft_2 <- add_header_row(final, values = c("Gender", "Party"), colwidths = c(1, 3), top = TRUE)

ft_2 <- width(ft_2, j=1, 3/2.54)

ft_2 <- align(ft_2, align = "center", part = "header")

ft_2 <- border_outer(ft_2, fp_border(color="black", width=1.5))

ft_2 <- border_inner(ft_2, fp_border(color="gray"))

ft_2 <- fix_border_issues(ft_2)

ft_2 %<>% bold(part = "header")

ft_2 %<>% bold (i = c(1,2),
               j = 1, bold = TRUE)

ft_2

它看起来像这样:

我想问我们如何引用多行标题中的单元格,以便正确合并它们,这意味着删除某些单元格之间的一些边框。我知道对于行我们引用i=,对于列我们引用j=,但是如何引用扩展标题中的单元格呢?我想要的结果是:
1.变量:

2.变量:

请问我该怎么做。任何帮助将不胜感激。此外,我想问如何中心性别时,下面的线已被删除。
我已经尝试了到目前为止的代码是放在上面和我的预期结果描述以及。

o2rvlv0m

o2rvlv0m1#

这应该回答:
1.如何合并
1.如何添加特定边框

ft_2 |> 
  merge_at(i = 1:2, j = "gender", part = "header") |> 
  hline_bottom(border = fp_border(color = "red"), part = "header") |> 
  vline(j = "gender", border = fp_border(color = "red"), part = "all") |> 
  fix_border_issues() # fix side effects of cell merging

请注意,您也可以使用proc_freq,它会产生类似的结果:

library(flextable)
library(officer)
library(tidyverse)

M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(
  gender = c("F", "M"),
  party = c("Democrat", "Independent", "Republican"))

M <- as.data.frame(M) |> uncount(Freq)

proc_freq(M, row = "gender", "party",
          include.row_percent = FALSE, 
          include.column_percent = FALSE,
          include.table_percent = TRUE,
          )

相关问题