如何在没有标题的情况下向 flextable 添加标题?

huangapple go评论58阅读模式
英文:

Given a flextable without a header how can I add a header?

问题

如果我有一个没有标题的flextable,如何添加一个标题?在下面的示例中,我是人为地设置了这种情况。也就是说,我想将flexiris_without_head还原成flexiris_with_head

library(flextable) # 版本 0.9.2

flexiris_with_head <- flextable(iris)
flexiris_with_head

flexiris_without_head <- flexiris_with_head %>%
  delete_part(part = "header")
flexiris_without_head

如果有人对更多背景信息感兴趣:
我主要使用huxtable对象,但是出于docx输出的目的,我需要将其转换为flextable对象。使用huxtable::as_flextable()会导致我没有(技术上的)标题,这对于长表格是一个问题,因为标题不再滚动到下一个docx页面。

英文:

If I have a flextable without a header, how can I add one? In the example below I am setting the scenario up artificially. i.e. I would like to turn flexiris_without_head back into flexiris_with_head.

library(flextable) # version 0.9.2

flexiris_with_head &lt;- flextable(iris)
flexiris_with_head

flexiris_without_head &lt;- flexiris_with_head %&gt;%
  delete_part(part = &quot;header&quot;)
flexiris_without_head

If anyone is interested in more context:
I am primarily working with huxtable objects, which I, however, need to translate to flextable objects for docx output purposes. Using huxtable::as_flextable() leaves me without a (technical) header, which is an issue for long tables because the headers do not roll over to the next docx page anymore.

答案1

得分: 1

以下是使用add_header_row()的一种方法:

library(dplyr)
library(flextable)

# 创建 flextable
df <- flextable(head(iris))

# 删除 iris 表格的头部 -> df_without_header
df_without_header <- df %>%
  delete_part(part = "header")

# 向 flextable 添加头部
df_with_header <- df_without_header %>%
  add_header_row(
    values = colnames(iris), 
    top = TRUE
  ) %>%
  hline_top(part = "header") %>%
  hline_bottom(part = "header")

df_with_header

如何在没有标题的情况下向 flextable 添加标题?

英文:

Here is one way how we could do it using add_header_row():

library(dplyr)
library(flextable)

# flextable
df &lt;- flextable(head(iris))

# iris without header -&gt; df
df_without_header &lt;- df %&gt;%
  delete_part(part = &quot;header&quot;)

# adding header to flextable
df_with_header &lt;- df_without_header %&gt;%
  add_header_row(
    values = colnames(iris), 
    top = TRUE
  ) %&gt;%
  hline_top(part = &quot;header&quot;) %&gt;%
  hline_bottom(part = &quot;header&quot;)

df_with_header

如何在没有标题的情况下向 flextable 添加标题?

huangapple
  • 本文由 发表于 2023年7月20日 16:05:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定