gpt4 book ai didi

r - 按列灵活分组

转载 作者:行者123 更新时间:2023-12-05 02:55:38 25 4
gpt4 key购买 nike

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

enter image description here

我曾尝试使用 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 column
myft = merge_v(myft, j=c("Time", "Athlete"))
myft

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

最佳答案

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

时间顺序安排后,您可以使用flextable中的merge_v。添加了 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

输出

flextable with merged vertical column

关于r - 按列灵活分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61133385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com