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’sofficerpackage.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 theofficerpackage.
install.packages("officer")
We’ll also be using thedplyrpackage, 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.
library(officer)library(dplyr)
Now, we’ll get started creating a report! First, we will use theread_docxfunction to create an empty Word file.
# create empty Word filesample_doc <- read_docx()
Adding paragraphs
Next, let’s add a few sample paragraphs. We can do that using thebody_add_parfunction like below. The syntax is similar to that of thetidyverse.
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 thebody_add_tablefunction. 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 framedf <- data.frame(a = 1:10, b = 11:20, c= 21:30) # add table containing the data frame's contentssample_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,ggplotcould also be used.
set.seed(0) # create a temp filesrc <- tempfile(fileext = ".png") # create PNG objectpng(filename = src, width = 4, height = 4, units = 'in', res = 400) # create plotplot(sample(100, 10)) # save PNG filedev.off() # add PNG image to Word documentsample_doc <- sample_doc %>% body_add_img(src = src, width = 4, height = 4, style = "centered")
Lastly, we can save our Word Document usingprint.
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 intoread_docx. Then, we can continue modifying our Word Document object like we were previously.
sample_doc <- read_docx("sample_file.docx") # add another paragraphsample_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 sameread_docxfunction like we did above to modify an existing file. Secondly, we use thedocx_summarywith this object to get the content within the file.
sample_data <- read_docx("sample_file.docx") content <- docx_summary(sample_data)
docx_summaryreturns 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")paragraphs$text
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 columnssplits <- split(table_data, table_data$cell_id)splits <- lapply(splits, function(x) x$text) # combine columns back together in wide formattable_result <- bind_cols(splits) # get table headerscols <- table_cells %>% filter(is_header)names(table_result) <- cols$text
Conclusion
officercan 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 onofficer, check outthis link.
Visit TheAutomatic.net for additional insight on this topic.
Related Tags
Data Science R rstats RStudio
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 TheAutomatic.net and is being posted with its permission. The views expressed in this material are solely those of the author and/or TheAutomatic.net 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 circ*mstances and, as necessary, seek professional advice.