Reputation: 3200
When creating tables in Word reports, I often want to add blank rows in between variables. As a trivial toy example:
library(dplyr)
library(officer)
library(flextable)
doc <- read_docx()
table_no_breaks <- mtcars %>%
count(cyl)
table_no_breaks_ft <- flextable(table_no_breaks)
doc <- doc %>%
body_add_flextable(table_no_breaks_ft) %>%
body_add_par("")
Results in a table that looks like this:
I can add line breaks directly to the data frame like this:
table_breaks <- table_no_breaks %>%
mutate(
across(
everything(),
as.character
)
) %>%
add_row(cyl = NA, n = NA, .after = 1) %>%
add_row(cyl = NA, n = NA, .after = 3) %>%
add_row(cyl = NA, n = NA, .after = 5)
table_breaks_ft <- flextable(table_breaks)
doc <- doc %>%
body_add_flextable(table_no_breaks_ft) %>%
body_add_par("") %>%
body_add_flextable(table_breaks_ft)
print(doc, "flextable.docx")
Which results in the Word table that I want:
However, I would prefer to be able to add the blank rows directly to the flextable rather than the data frame the flextable is built from. To me, this is a formatting issue rather than a data issue, and I prefer to keep data issues (manipulation of data frames) and formatting issues (manipulation of Word tables) separate. Any advice is greatly appreciated!
Upvotes: 1
Views: 2879
Reputation: 4370
Very late to this but what if you just add padding to the table example below? Is the issue that you want actual blank rows or just spacing between rows?
library(dplyr)
library(flextable)
table_no_breaks <- mtcars %>%
count(cyl)
table_breaks <- table_no_breaks %>%
mutate(
across(
everything(),
as.character
))
flextable(table_no_breaks) |>
padding(padding = 15, part = "all")
edit: if you want to only pad certain rows you can use the i
and j
inputs to specify certain rows and columns to pad. Example below:
flextable(table_no_breaks) |>
padding(i= 2, padding = 15, padding.top = TRUE) |>
align(align = "center", part = "all")
Upvotes: 2