我正在R中使用flextable-function来创建漂亮的平面列联表。我的平面列联表具有两行列标题。我尝试使用flextable-package中的set_header_labels
函数更改这些设置,但失败了。
下面的步骤代表了我所经历的过程。前五个步骤运行良好。在最后一步中,我想将列标题名称从“ A”更改为“ aa”,从“ B”更改为“ bb”,但未能达到期望的结果。请注意,一开始将“ A”更改为“ aa”等并不能解决我的问题。我真的需要在最后而不是开始时进行所需的更改!
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))
ft <- (t %>% ftable(row.vars = c("q1"), col.vars = c("header1", "header2")))
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
}
flext <- ftable_to_flextable(ft)
flext <- merge_at(flext, i = 1, j = 2:3, part = "header")
flext <- merge_at(flext, i = 1, j = 4:5, part = "header")
正在运行flext
现在返回:
set_header_labels(flext, A = "aa", B = "bb")
我收到以下错误消息:
Error in `[<-`(`*tmp*`, i, j, value = value) : subscript out of bounds