Search code examples
rpivot-tableflextable

R flextable proc_freq remove counts


I want to show a crosstab of two variables in a flextable, but only show row/column/table percentages, not counts.

For example, if I run the collowing code

library(flextable)
proc_freq(mtcars,"cyl","gear",include.row_percent = FALSE,include.table_percent = FALSE )

I get the cross-tab with column percentages AND counts. How do I remove the counts?

I realize this can't be done with preexisting options, but I'm hoping it is easy to change the proc_freq function to remove the counts. Going over the code for the function, I can't see how I would do that.

Any thoughts?


Solution

  • The problem is that you are using a function designed to calculate and show frequency counts, which probably explains why there is no option to suppress them. You could use compose by removing text chunks in the unwanted cells:

    proc_freq(mtcars, "cyl", "gear",
              include.row_percent = FALSE,
              include.table_percent = FALSE ) |>
      compose(i=c(1,3,5), j=2:6, as_paragraph('')) |>
      compose(i=7, j=1, as_paragraph('')) |>
      compose(i=2, j=6, part="header", as_paragraph(''))
    

    enter image description here

    If you want a more general solution, then you could write a function that determines which rows and columns to edit based on the arguments provided.

    proc_freq2 <- function(data, ...) {
    
      x <- dplyr::select(data, ...) |>
        table()
    
      proc_freq(data, ...,
                include.row_percent=FALSE, include.table_percent = FALSE) |>
        compose(i=seq(1, 2*nrow(x) + 1, by=2), j=2:(ncol(x)+3), as_paragraph('')) |>
        compose(i=2*nrow(x)+1, j=1, as_paragraph('')) |>
        compose(i=2, j=ncol(x)+3, part="header", as_paragraph(''))
    }
    
    proc_freq2(mtcars, "cyl", "gear") # as above
    proc_freq2(mtcars, "carb", "vs")
    

    enter image description here