【发布时间】:2019-12-16 13:45:13
【问题描述】:
我正在使用 R 中的 flextable-function 创建一个漂亮的平面列联表。我的平面列联表有两行列标题。我尝试使用 flextable-package 中的 set_header_labels-function 更改这些,但失败了。
以下步骤代表我经历的过程。前五个步骤很顺利。在我想将列标题名称从“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")))
- 加载函数以将平面列联表转换为弹性表。来源: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
}
- 创建一个弹性表。
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
【问题讨论】:
-
看起来问题在于您使用了两个标题行。尝试只使用一个,效果很好。