繁体   English   中英

flextable 按列分组

[英]flextable group by column

我正在通过 Rmarkdown 生成需要能够呈现到 Word 的报告。 我希望能够重现这种表格格式:

在此处输入图像描述

我曾尝试使用flextable来做到这一点,但没有任何实际进展。 我已经通读了flextable站点,并找到了一种使用组来合并行而不是对列进行分组的方法。 as_grouped_data() function 可以预先创建组,但是我可以将这些组用于列标题吗?

我的数据的小例子:

df = structure(list(Athlete = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Athlete 1", "Athlete 2"), class = "factor"), 
    Time = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 
    2L, 3L), .Label = c("1", "2", "3"), class = "factor"), Measure = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Distance", 
    "Speed"), class = "factor"), Value = c(4.02, 11.5, 19.82, 
    3.03, 9.67, 17.9, 6.5, 8.08, 8.47, 5.3, 7.64, 8.67)), row.names = c(NA, 
-12L), class = "data.frame")
# Create table
myft = flextable(df) 
# Merge athlete coloumn
myft = merge_v(myft, j=c("Time", "Athlete"))
myft

我被困在这里,不确定如何将这些组从行标题旋转到列标题。

要为表格创建所需的格式,您可能需要“宽”数据。 这将为您的 2 位运动员提供 2 列。 此示例使用来自pivot_widertidyr

Time顺序排列后,您可以使用merge_v中的flextable 添加fix_border_issues以在合并后修复底部表格边框。

library(flextable)
library(tidyverse)

myft <- df %>%
  pivot_wider(id_cols = c(Time, Measure), names_from = Athlete, values_from = Value) %>%
  arrange(Time) %>%
  flextable()

# Merge Time column vertically
myft = merge_v(myft, j="Time")
myft = fix_border_issues(myft, part = "all")
myft

Output

具有合并垂直列的弹性表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM