我如何在R中有多个标题行的柔性表中设置标题标签?

问题描述 投票:1回答:1

我正在R中使用flextable-function来创建漂亮的平面列联表。我的平面列联表具有两行列标题。我尝试使用flextable-package中的set_header_labels函数更改这些设置,但失败了。

下面的步骤代表了我所经历的过程。前五个步骤运行良好。在最后一步中,我想将列标题名称从“ A”更改为“ aa”,从“ B”更改为“ bb”,但未能达到期望的结果。请注意,一开始将“ A”更改为“ aa”等并不能解决我的问题。我真的需要在最后而不是开始时进行所需的更改!

  1. 创建小标题。
t <- tibble(ID = 1:10, 
header1 = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
header2 = c("No", "No", "No", "Yes", "Yes", "Yes", "Yes", "No", "Yes", "No"),
q1 = c(1, 3, 2, 2, 3, 1, 2, 1, 1, 3))
  1. 创建平坦的列联表。

ft <- (t %>% ftable(row.vars = c("q1"), col.vars = c("header1", "header2")))

  1. 加载将平面列联表转换为弹性表的函数。来源:Is there an (easy) way to convert flat contingency tables (ftable) to flextable
ftable_to_flextable <- function( x ){

  row.vars = attr( x, "row.vars" )
  col.vars = attr( x, "col.vars" )
  rows <- rev(expand.grid( rev(row.vars), stringsAsFactors = FALSE ))
  cols <- rev(expand.grid( rev(col.vars), stringsAsFactors = FALSE ))

  xmat <- as.matrix(x)
  cols$col_keys = dimnames(xmat)[[2]]
  xdata <- cbind(
    data.frame(rows, stringsAsFactors = FALSE),
    data.frame(xmat, stringsAsFactors = FALSE)
  )
  names(xdata) <- c(names(row.vars), cols$col_keys)

  ft <- regulartable(xdata)
  ft <- set_header_df(ft, cols)
  ft <- theme_booktabs(ft)
  ft <- merge_v(ft, j = names(row.vars))
  ft
}
  1. 创建弹性表。

flext <- ftable_to_flextable(ft)

  1. 合并两个标题标题。
flext <- merge_at(flext, i = 1, j = 2:3, part = "header")
flext <- merge_at(flext, i = 1, j = 4:5, part = "header")

正在运行flext现在返回:

enter image description here

  1. 现在,我想更改平面列联表的第一标题行中的两个标签。

set_header_labels(flext, A = "aa", B = "bb")

我收到以下错误消息:

Error in `[<-`(`*tmp*`, i, j, value = value) : subscript out of bounds
r label flextable
1个回答
0
投票
这应该用您的代码完成工作
© www.soinside.com 2019 - 2024. All rights reserved.