使用 flextable 中的 add_header_row 创建不同宽度的列

2024-04-25

我有数据如下:

dat <- structure(list(rn = c("type_A", "type_B", "type_C"
), freq = list(c(0, 0, 0, 5, 7, 16, 28), c(2, 1, 0, 5, 0, 8), 
    c(0, 0, 3, 5, 12, 53, 73)), colspan = list(c(`25` = 1, `100` = 2, 
`250` = 1, `500` = 1, `1000` = 1, Infinity = 3, SUM = 1), c(`25` = 1, 
`100` = 2, `250` = 1, `500` = 1, Infinity = 4, SUM = 1), c(`25` = 1, 
`50` = 1, `100` = 1, `250` = 1, `500` = 1, Infinity = 4, SUM = 1
))), row.names = c(NA, 3L), class = "data.frame")

total_colspan = c(0, 25, 50, 100, 250, 500, 1000, 1500, 3000, "Infinity", "SUM")

      rn                   freq             colspan
1 type_A  0, 0, 0, 5, 7, 16, 28 1, 2, 1, 1, 1, 3, 1
2 type_B       2, 1, 0, 5, 0, 8    1, 2, 1, 1, 4, 1
3 type_C 0, 0, 3, 5, 12, 53, 73 1, 1, 1, 1, 1, 4, 1

我想创建一个具有不同列跨度的表(但它们加起来都是10),在R-markdown Word文档中,如下表:

有人建议我尝试flextable为了这 (link https://ardata-fr.github.io/flextable-book/)。我正在尝试使用标头选项来创建这些不同的 colspan。我想过做类似的事情:

dat_table <- flextable(dat)
dat_table <- lapply(dat_table, add_header_row, values = unlist(freq), colwidths = unlist(colspan))

但这是行不通的。

EDIT:

我的第二次尝试:

dat <- structure(list(rn = c("type_A", "type_B", "type_C"
), freq = list(c(0, 0, 0, 5, 7, 16, 28), c(2, 1, 0, 5, 0, 8), 
    c(0, 0, 3, 5, 12, 53, 73)), colspan = list(c(1, 2, 1, 1, 1, 3, 1),  c(1, 2, 1, 1, 4, 1), c(1, 1, 1, 1,  1, 4, 1
))), row.names = c(NA, 3L), class = "data.frame")

# The thresholds as in the picture
thresholds <- data.frame(c("Lower threshold","Upper threshold"), c(0,25), c(25,50), c(50,100), c(100,250), c(250,500),c(500,1000),c(1000,1500),c(1500,3000),c(3000, "Infinity"), c("", "SUM"))
names(thresholds) <- c("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven")
thresholds <- flextable(thresholds)

# There was one column to few in the example
dat <- transform(dat, colspan=Map('c', 1, dat[["colspan"]] ))
dat <- transform(dat, freq=Map('c', "", dat[["freq"]] ))

# for loop to stick to the syntax
for (i in nrow(dat)) {
 thresholds <- add_header_row(thresholds, values = dat[[2]][[i]], colwidths = dat[[3]][[i]])
}

由于某种原因,它只添加一行(虽然它允许添加更多标题)。


这是一个可能太过分的解决方案,但似乎可以满足您的需求:

library(tidyverse)
library(flextable)

dat <- structure(list(rn = c("type_A", "type_B", "type_C"
), freq = list(c(0, 0, 0, 5, 7, 16, 28), c(2, 1, 0, 5, 0, 8), 
               c(0, 0, 3, 5, 12, 53, 73)), colspan = list(c(1, 2, 1, 1, 1, 3, 1),  c(1, 2, 1, 1, 4, 1), c(1, 1, 1, 1,  1, 4, 1
               ))), row.names = c(NA, 3L), class = "data.frame")

# The thresholds as in the picture
thresholds <- data.frame(c("Lower threshold","Upper threshold"), c(0,25), c(25,50), c(50,100), c(100,250), c(250,500),c(500,1000),c(1000,1500),c(1500,3000),c(3000, "Infinity"), c("", "SUM"))
names(thresholds) <- c("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven")

out <- map(1:nrow(dat), function(index){
  out <- data.frame("freq" = dat$freq[[index]], 
                    "span" = dat$colspan[[index]]) %>% 
    tidyr::uncount(span, .id = 'span') %>% 
    mutate(freq = ifelse(span>1, NA, freq)) %>% 
    t %>% 
    as.data.frame() %>% 
    mutate(rn = dat$rn[[index]],
           across(everything(), ~as.character(.))) %>% 
    select(rn, everything()) %>% 
    set_names(nm = names(thresholds)) %>% 
    slice(1)
  return(out)
}) 

combined <- thresholds %>% 
  mutate(across(everything(),  ~as.character(.))) %>% 
  bind_rows(out) 

spans <- map(1:length(dat$colspan), function(index){
  spans <- dat$colspan[[index]] %>%  
    as_tibble() %>% 
    mutate(idx = row_number()) %>% 
    tidyr::uncount(value, .remove = F) %>% 
    group_by(idx) %>%
    mutate(pos = 1:n(),
           value = ifelse(pos != 1, 0, value)) %>% 
    ungroup() %>% 
    select(value) %>% 
    t
  return(append(1, spans))
})

myft <- flextable(combined) %>% 
  theme_box()

myft$body$spans$rows[3:nrow(myft$body$spans$rows),] <- matrix(unlist(spans), ncol = ncol(combined), byrow = TRUE)

myft

Created on 2022-04-29 by the reprex package https://reprex.tidyverse.org (v2.0.1)

这使得该表:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 flextable 中的 add_header_row 创建不同宽度的列 的相关文章

  • 使用 ggplot 未完全填充等值线图

    我正在尝试使用以下方法绘制我的第一个填充等高线图ggplot 根据我的数据 我期待类似的结果 但我的结果是 a lt c 1 1 1 1 1 3 1 2 2 2 2 2 2 5 2 1 3 3 3 3 1 3 2 b lt c rep c
  • R源代码.调用函数[重复]

    这个问题在这里已经有答案了 我正在查看R中cov的source code 并遇到了一段我不太明白的代码 协方差的数学定义goes http en wikipedia org wiki Covariance here if method pe
  • 通过删除连续的重复项来减少字符串长度

    我有一个包含 2 个字段的 R 数据框 ID WORD 1 AAAAABBBBB 2 ABCAAABBBDDD 3 我想通过仅保留字母而不是重复中的重复项来简化具有重复字母的单词 e g AAAAABBBBB应该给我AB and ABCAA
  • 用于不规则时间序列的滚动窗口函数,可以处理重复项

    我有以下数据框 grp nr yr 1 A 1 0 2009 2 A 2 0 2009 3 A 1 5 2009 4 A 1 0 2010 5 B 3 0 2009 6 B 2 0 2010 7 B NA 2011 8 C 3 0 2014
  • ggplot() 使用scale::percent_format() 缩放产生奇怪的结果

    library tidyverse mtcars gt count cyl gt mutate prop n sum n gt ggplot aes x cyl y prop geom point scale y continuous la
  • 如何更改数据表中的少数列名称

    我有一个包含 10 列的数据表 town tc one two three four five six seven total 需要生成我正在使用的列 一 到 总计 的平均值 DTmean lt DT lapply SD mean by t
  • Python:两个列表之间的成对比较:列表 a >= 列表 b?

    如果我想检查列表中的所有元素 a 1 2 3 6 大于或等于另一个列表中对应的元素 b 0 2 3 5 如果 a i gt b i 对于所有i的 则返回 true 否则返回 false 这有逻辑功能吗 比如a gt b 谢谢 你可以这样做
  • 替换向量中非 %in% 向量的值

    简短的问题 我可以像这样替换某些变量值 values lt c a b a b c a b df lt data frame values 将 df values 的所有值替换为 x 其中值是neither a 或 b 输出应该是 c a
  • 使用 R:如何创建带有日期的时间序列对象?

    我有一年中每小时采集的一系列值 是否可以创建一个保留小时和年份值的时间序列对象 我的代码使用股票价格第一列中的值 但不使用日期 stockprices ts lt ts stockprices 1 start 1 freq 168 您没有提
  • 为什么 data.table `:=` 的 knit 缓存失败?

    这在精神上与this https stackoverflow com q 15267018 1900520问题 但机制上一定不同 如果您尝试缓存knitr包含一个块data table 分配然后它的行为就好像该块尚未运行 并且后面的块看不到
  • ggplot2 中的小时刻度

    我正在处理就寝时间和醒来时间 因此我想创建一个具有 24 小时 x 轴的图表 从第一天中午 12 点开始 到第二天中午 12 点结束 这意味着晚上 11 59 之后 它应该再次从 0 开始 同样的问题 仅涉及数字 我想创建一个从 10 到
  • 带有 geom_errorbar 的position_dodge

    我有以下代码 require ggplot2 pd lt position dodge 0 3 ggplot dt aes x Time y OR colour Group geom errorbar aes ymin CI lower y
  • mclapply 调用应该嵌套吗?

    正在筑巢parallel mclapply是个好主意吗 require parallel ans lt mclapply 1 3 function x mclapply 1 3 function y y x unlist ans Outpu
  • 使用 igraph 将边缘属性显示为标签

    我在 R 中使用 igraph 进行网络分析 我想在图中的每条线上显示边缘属性 下面是一个例子 df lt data frame a c 0 1 2 3 4 b c 3 4 5 6 7 nod lt data frame node c 0
  • Openxlsx 多次验证损坏输出文件

    我正在尝试添加多个验证并将公式添加到 Excel 文件 这是我使用的代码 library openxlsx fileTemplate lt New01 xlsx wbTemplate lt loadWorkbook fileTemplate
  • 如何使用 tweepy 仅提取主题标签中的文本?

    我想为我的情感分析项目提取主题标签 但是我得到了一个字典列表 其中包含所有主题标签及其在推文中的索引 我只想要文字 我的代码 data tweepy Cursor api search q since a i until b i items
  • R dplyr过滤多列上的字符串条件

    我有一个 df 例如 df lt read table text v1 v2 v3 v4 v5 1 A B X C 2 A B C X 3 A C C C 4 B D V A 5 B Z Z D header T 如果变量 v2 到 v5
  • 使用 purrr::map() 更改和分配新变量名称

    我刚刚开始掌握编写函数并使用 lapply purrr map 使我的代码更加简洁 但显然还没有完全理解它 在我当前的示例中 我想重命名 lm robust 对象的系数名称 然后更改 lm robust 对象以合并新名称 我目前这样做 li
  • 列槽不足

    当尝试为 data table 中的每个变量 108 个变量 创建 12 个滞后时 我收到一条错误 指出列槽不足 此操作应创建大约 1200 个变量或列 Data A as data table Datos A Varnames names
  • ggplot堆叠条 - 隐藏标签但保留标签位置

    我在 ggplot 中有一个堆积条形图 其中 geom text 标签位于每个条形的中心 我想隐藏小条上的标签 以便图表看起来不会过于拥挤 我可以使用下面的代码来完成此操作 但它会弄乱标签的位置 正如您在下面的链接图片中看到的那样 它们不再

随机推荐