Search code examples
rdataframecharacterofficer

Export data.table and print cells content in new lines


Let's have a data frame:

df <- data.frame(c('Warsaw; Nairobi'),c('Mogadishu; Ottawa'),c('Berlin; Paris'))
colnames(df)<-c('a','b','c')

Now it is time to export data to table .docx

library(officer)
library(flextable)
library(magrittr)
my_doc <- read_docx()
export <- my_doc%>%body_add_table(df)
print(export, target = "my_path/table.docx")

I want to exchange semicolons to sign that will force the MS Word to print the capital cities in new lines within the same cell.

Like column on the right:

enter image description here


Solution

  • Replace ; with \n:

    df$a <- gsub("; ", "\\\n", df$a)
    df$b <- gsub("; ", "\\\n", df$b)
    df$c <- gsub("; ", "\\\n", df$c)
    
    flextable(df)
    

    enter image description here