0

I am preparing a function to create table output from a categorical variable that can be exported to word using flextable and officer library.

libraries needed:

library(dplyr)
library(officer)
library(flextable)

Function is:

tab_std<-function(data, var, Name_of_variable, footer, Title) { 
  data <- data[!is.na(data[[var]]), ]
  T1 <- as.data.frame(table(data[[var]]))
  all <- sum(T1[, 2])
  T1 <- T1 %>% mutate(
    !!Name_of_variable := as.character(Var1),
    "Percent" = roundUp(Freq * 100 / all),
    "N" = as.numeric(Freq)
  ) %>%
    select(!!Name_of_variable, "Percent", "N")
  T1[ ,2]<-sapply(T1[,2], function(x) ifelse(x=="--","--",paste0(mask_m(x,all),"%")))

  T1%>% flextable()%>% add_header_lines(Title)%>% add_footer_lines(footer)
}

Functions that are used within in this function are:

masking_criteria<-c(3,4,5)

mask_m<-function(x,N){
  x= ifelse(N<masking_criteria[1],"--",x)
}

With this function I am adding Title to the table using function add_header_lines(), but this adds the title as part of the table. I want the title to be displayed as a text on the top of the table should not be a row of the table. For examples:

test<-data.frame(gender=c("M","M","F",NA),Names=c("A","B","C","D"),Amount=c(3,4,2,5))
tab_std(test, "gender","Gender","This is the footer","This is my Title")

Is there any possible way to add title on the top within this function?

  • Are you using Word output (with read_docx)? – David Gohel Mar 03 '20 at 21:45
  • Yes, i am using a word template to export the tables with read_docx – Sandhya Ghildiyal Mar 06 '20 at 06:27
  • OK, sorry, it was written at the top of the post. I read that too fast. I think you are after a caption, this wiill be a feature soon. Meanwhile, you can reproduce a caption with officer::body_add_par or officer::body_add_fpar. But this can not be part of the flextable, you will need two calls, one to add the flextable and the other to add the caption – David Gohel Mar 06 '20 at 08:03
  • Thanks, i am trying that, but not able to print the title – Sandhya Ghildiyal Mar 06 '20 at 14:35

1 Answers1

0

You can try using a new package called {rrtable}. It allows you to output flextable object while adding an additional line as the title. Please see function add_text().

Angel Lu
  • 11
  • 2