简体   繁体   中英

Adding title to the table with flextable and officer library

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?

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM