按列灵活分组
flextable group by column
我正在通过 Rmarkdown 生成需要能够呈现到 Word 的报告。我希望能够重现这种 table 格式:
我已经尝试使用 flextable
来做到这一点,但没有任何实际进展。我通读了 flextable
站点并找到了一种使用组来合并行而不是对列进行分组的方法。 as_grouped_data() 函数可以预先创建组,但我可以将这些组用作列标题吗?
我的数据的小例子:
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
我被困在这里,不确定如何将这些组从行标题旋转到列标题。
要为 table 创建您想要的格式,您可能需要数据 "wide." 这将为您的 2 名运动员提供 2 列。此示例使用来自 tidyr
.
的 pivot_wider
按 Time
顺序排列后,您使用 flextable
中的 merge_v
。添加 fix_border_issues
以在合并后修复底部 table 边框。
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
输出
我正在通过 Rmarkdown 生成需要能够呈现到 Word 的报告。我希望能够重现这种 table 格式:
我已经尝试使用 flextable
来做到这一点,但没有任何实际进展。我通读了 flextable
站点并找到了一种使用组来合并行而不是对列进行分组的方法。 as_grouped_data() 函数可以预先创建组,但我可以将这些组用作列标题吗?
我的数据的小例子:
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
我被困在这里,不确定如何将这些组从行标题旋转到列标题。
要为 table 创建您想要的格式,您可能需要数据 "wide." 这将为您的 2 名运动员提供 2 列。此示例使用来自 tidyr
.
pivot_wider
按 Time
顺序排列后,您使用 flextable
中的 merge_v
。添加 fix_border_issues
以在合并后修复底部 table 边框。
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
输出