Is there an (easy) way to convert flat contingency tables (ftable) to flextable

风流意气都作罢 提交于 2020-08-11 05:57:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!