Multilingual content from IBKR

Close Navigation
Learn more about IBKR accounts
How to Read and Create Word Documents in R

How to Read and Create Word Documents in R

Posted February 18, 2022 at 12:52 pm
Andrew Treadway

Reading and creating word documents in R

In this post we’ll talk about how to use R to read and create word files. We’ll primarily be using R’s officer package. For reading data from Word Documents with Python, click here.

Creating Word reports with the officer package

The first thing we need to do is to install the officer package.


We’ll also be using the dplyr package, so you’ll need to install that the same way if you don’t have it already. Next, let’s load each of these packages.


Now, we’ll get started creating a report! First, we will use the read_docx function to create an empty Word file.

# create empty Word file
sample_doc <- read_docx()

Adding paragraphs

Next, let’s add a few sample paragraphs. We can do that using the body_add_par function like below. The syntax is similar to that of the tidyverse.

sample_doc <- sample_doc %>% body_add_par("This is the first paragraph") 
sample_doc <- sample_doc %>% body_add_par("This is the second paragraph")
sample_doc <- sample_doc %>% body_add_par("This is the third paragraph")

Now, we can add a table to our document using the body_add_table function. Before we do that, we just need to have a data frame ready, so we’ll create a sample one like below.

# create sample data frame
df <- data.frame(a = 1:10, b = 11:20, c= 21:30)
# add table containing the data frame's contents
sample_doc <- sample_doc %>% body_add_table(df, style = "table_template")

Adding images to the document

We can also add images to our Word Document. This is done by creating a temp file with an R plot and then adding the image to our document object. Though we’re using base R for plotting here, ggplot could also be used.

# create a temp file
src <- tempfile(fileext = ".png")
# create PNG object
png(filename = src, width = 4, height = 4, units = 'in', res = 400)
# create plot
plot(sample(100, 10))
# save PNG file
# add PNG image to Word document
sample_doc <- sample_doc %>% body_add_img(src = src, width = 4, height = 4, style = "centered")

Lastly, we can save our Word Document using print.

print(sample_doc, target = "sample_file.docx")

How to modify existing Word Documents

To modify existing Word Documents, all we need to change is to input the filename into read_docx. Then, we can continue modifying our Word Document object like we were previously.

sample_doc <- read_docx("sample_file.docx")
# add another paragraph
sample_doc <- sample_doc %>% body_add_par("This is another paragraph")

How to read Word Documents with R

What if we want to read in the Word Document we just created? We can do that using the same read_docx function like we did above to modify an existing file. Secondly, we use the docx_summary with this object to get the content within the file.

sample_data <- read_docx("sample_file.docx")
content <- docx_summary(sample_data)

docx_summary returns a dataframe with the content in the Word file, as can be seen above. For example, to get the text in the paragraph of the document, we just need to filter the content_type field on “paragraph”, like below:

paragraphs <- content %>% filter(content_type == "paragraph")

Extracting tables from Word Documents

Now, let’s extract the table from our document. We can do this similarly to the above in that we just need to filter content_type for “table cell”:

content %>% filter(content_type == "table cell")

As you can see, the table’s columns are stacked in a single column. We need to do a little transformation to get this result into the needed format.

table_cells <- content %>% filter(content_type == "table cell")
table_data <- table_cells %>% filter(!is_header) %>% select(row_id, cell_id, text)
# split data into individual columns
splits <- split(table_data, table_data$cell_id)
splits <- lapply(splits, function(x) x$text)
# combine columns back together in wide format
table_result <- bind_cols(splits)
# get table headers
cols <- table_cells %>% filter(is_header)
names(table_result) <- cols$text


officer can also be used to interact with PowerPoint files, which we’ll cover in a future post. That’s all for now! Click here to follow my blog Twitter and get notified of new posts! For more on officer, check out this link.

Visit for additional insight on this topic.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from and is being posted with its permission. The views expressed in this material are solely those of the author and/or and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.