R语言 在弹性表的表中添加标题

beq87vna  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(118)

我正试图使用flextable来制作一个漂亮的表格,它与word结合在一起,并带有描述性的横幅/标题
示例数据:

trialdata<-structure(list(` ` = c("Number per team", "Average height", "vegetarian", 
"meat", "carrot", "cucumber", "orange", 
"banana", "pepper", "tangerine", "Average Score", 
"Range Score", "Number of children", "Number of parents", 
"Number of grandparents"), `year 1` = c("20", "2", 
"25", "12", "4", "7", 
"7", "37", "21", "3", 
"-0.3", "78 : 1", "61", "19", 
"39"), `Year 2` = c("98", "28.2", "23", 
"1", "8", "6", "1", 
"36", "2", "29", "-0.2", "3 : 2", 
"6", "18", "9"), `Year 3` = c("88", 
"28.2", "24", "1", "1", "4", 
"91", "3", "24 ", "2", 
"-0.2", "7 : 2", "58", "1", 
"8")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-15L))

创建一个表:

install.packages("flextable")
library(flextable)
table1<-flextable(trialdata)

这就形成了一个类似下图的表格,只有一个标题x1c 0d1x
然而,我想添加一些描述性的标题,例如“最喜欢的食物”。这不是数据中已经存在的“分组”,而是添加的文本,我想使表格更清晰,例如看起来像这样:

Flex表格有添加页眉和页脚的方法,但我看不到在表格中添加页眉类型对象的方法。

von4xj4u

von4xj4u1#

我不认为flextable会接受不在页眉/页脚位置的页眉/页脚,但这并不是说我们不能通过编程方式将类似的行添加到表中。

第一步:定义新的标题(我就称之为子标题)以及它们应该插入的位置:

sub.headers <- c("favourite foods", "other details")
insert.after <- c(4, 10)

第二步:定义一个函数,将它们作为新行插入到输入的表中,并输出结果:

process.data <- function(df, lab, pos) {
  lab <- rev(lab)
  pos <- rev(pos)
  for(i in seq_along(pos)) {
    # split data frame at insert location
    df1 <- df[seq(1, pos[i]), ]
    df2 <- df[seq(pos[i] + 1, nrow(df)), ]

    # create new data frame with same column names, but with the sub-header
    # as the value for 1st column
    df.add <- df %>% slice(1)
    df.add[1, 1] <- lab[i]

    # combine the result
    df <- rbind(df1, df.add, df2)
  }
  return(df)
}

第三步:将原始 Dataframe 通过函数传递,并对结果进行美化:

header.pos <- insert.after + seq.int(length(insert.after))
border.format <- officer::fp_border(width = 2)

trialdata %>%
  process.data(lab = sub.header,
               pos = insert.after) %>%
  flextable() %>%
  merge_h_range(i = header.pos, 
                j1 = 1, j2 = ncol(trialdata)) %>%
  bold(i = header.pos) %>%                            # bold
  hline(i = header.pos, border = border.format) %>%   # add line below
  hline(i = header.pos - 1, border = border.format)   # add line above

结果:

更改步骤1中的值将使您能够将其调整为其他 Dataframe 。

相关问题