In Word, it is possible to copy and paste a subsection of one table into another table. For example, if I have the two Word tables below, I can copy column 2, rows 2-5 from the first table and paste them into column 2, rows 4-7 in the second table.
I can highlight the cells that I want to copy in the first table and and paste them into the cells of the second table.
I'm wondering if there is a programmatic way to do a similar operation with flextable
and officer
. It's probably worth mentioning the following to parameters:
Creating the second table from scratch with the values from the first table included won't work for my problem -- or at least it's a solution that I'm trying to avoid.
Adding the values from the first table to the cells of the second table one at a time with bookmarks won't work for my problem -- or at least it's a solution that I'm trying to avoid.
I've tried the following potential solutions so far. They all begin with the following template Word document with bookmarks embedded in the table.
Additionally, here is the code I'm using to create the "First table" example data.
first_table <- tibble(
n_items = 1:4,
n = c(100, 40, 20, 5)
)
Method 1: Add values to a bookmark in the second table
Start by reading in the Word template document.
doc <- read_docx("embedding_flextables_in_existing_word_tables.docx")
Then, I tried adding the values from first_table to the bookmark in the second table.
doc <- doc %>%
body_replace_text_at_bkm(
"bm_add_rows_01",
first_table %>% pull(n) %>% as.character()
)
That code results in the following error:
Error in body_replace_text_at_bkm(., "bm_add_rows_01", first_table %>% :
is_scalar_character(value) is not TRUE
So, I can't add a vector of values to the bookmark.
Method 2: Add a single-column flextable to a bookmark in the second table
To do this, I need to first coerce first_table into a single-column flextable object.
first_table_ft <- first_table %>%
select(n) %>%
flextable() %>%
delete_part("header") %>%
border_remove()
Then, add the single-column flextable to the bookmark in the second table.
doc <- doc %>%
body_replace_flextable_at_bkm("bm_add_rows_01", first_table_ft)
print(
doc,
"embedding_flextables.docx"
)
That returns the following result -- a four-row table embedded into a single cell of the second table. This result makes sense, but it isn't the result I'm attempting to achieve.
Method 3: Add a single-column flextable to a bookmark in the second table with cells merged vertically
For my third attempt, I tried adding the bookmark to the second table with rows 4-7 merged in column 2.
Then, adding the single-column flextable to the bookmark in the second table as before.
doc <- doc %>%
body_replace_flextable_at_bkm("bm_add_rows_02", first_table_ft)
print(
doc,
"embedding_flextables.docx"
)
Which again returns a result that isn't quite what I'm looking for.
Any solutions and/or constructive feedback is appreciated!