问题
I used to create FlexTable-objects from ‘flat’ contingency tables (ftable, stats-package) based on the old packages reporteRs and rtable. Before these packages became obsolete and were removed from CRAN, there has been a function as.Flextable.ftable, which did the trick.
--> See: https://rdrr.io/cran/rtable/man/as.FlexTable.ftable.html
Is there a way to achieve this conversion for the new flextable package? I couldn't find a similar function yet.
回答1:
that a very good question. The migration has started but not finished yet. Below a code that should do the job for now:
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
}
library(flextable)
library(magrittr)
ftable(Titanic, row.vars = 1:3) %>% ftable_to_flextable()
ftable(Titanic, row.vars = 1:2, col.vars = "Survived") %>% ftable_to_flextable()
ftable(Titanic, row.vars = 2:1, col.vars = "Survived") %>% ftable_to_flextable()
来源:https://stackoverflow.com/questions/52661289/is-there-an-easy-way-to-convert-flat-contingency-tables-ftable-to-flextable