<p>In the digital age of today, data comes in many forms. Many of the more common file types like CSV, XLSX, and plain text (TXT) are easy to access and manage. Yet, sometimes, the data we need is locked away in a file format that is less accessible such as a PDF. If you have ever found yourself in this dilemma, fret not — pdftools has you covered.</p>
<p>In this post, you will learn how to: usepdftools to extract text from a PDF, use the stringr package to manipulate strings of text, and create a tidy data set. In anticipation of March Madness and being a University of Cincinnati alumnus along with some other my other Datazar constituents, I have chosen to extract season <a rel="nofollow" href="http://gobearcats.com/documents/2018/3/10/Cincinnati_Season_League_Stats.pdf" target="_blank">statistics</a> from the UC men’s basketball team. In the end, I will create a <a rel="nofollow" href="http://tibble.tidyverse.org/" target="_blank">tibble</a> showing season statistics for minutes played, field goal percentage, total points, and average points per game for each player.</p>
<p>The first step is to load the packages that are needed using library(). The stringr package is a member of the tidyverse collection of R packages (more on that <a rel="nofollow" href="https://www.tidyverse.org/" target="_blank">here</a> if you are not familiar). The packages in therein are designed to make data science easy. I highly recommend purchasing <em>R for Data Science</em> by Hadley Wickham and Garrett Grolemund. It is a great book for beginners as well as a pocket reference for more advanced programmers. I use this book almost every day — it goes where I go.</p>
<figure><img alt="" src="https://i0.wp.com/cdn-images-1.medium.com/max/995/1*r38QQLZ6P1segHIPOJU7kw.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>The next step is to <a rel="nofollow" href="https://docs.datazar.com/guides/how_to_import_files_to_a_notebook_or_console/" target="_blank">load</a> your PDF into your Datazar project. I am going to call my new object ‘UC_text’ and I am going to use the pdf_text command to read the text of my file. The read_lines() function reads the lines of our new file.</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/993/1*l4JwmbH4-PpS5iGFJxsZEw.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>I want to focus on the season statistics of the players, which makes up lines 9 through 24 of our new file. Line 9 consists of the column names of our resulting data frame. I am going to call this new object season_stats.</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/995/1*hPstpLUBE4EYxCY9-Jdr2g.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>In the next series of steps, I will use functions in the stringr package to manipulate the lines of text into a desirable form. The first problem to tackle is the whitespace between the different elements in each line of text. The str_squish function reduces the repeated whitespace between each string. I also need to remove the comma between each player’s first and last name. I’ll use str_replace_all to remove the comma.</p>
<figure><img alt="" src="https://i0.wp.com/cdn-images-1.medium.com/max/993/1*hIuLerPjqDKja0tnm88zJw.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>After the whitespace and the commas have been removed, I can focus on separating each element. I will use strsplt to split the elements of each string into substrings.</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/995/1*Ycaxv9HRnd7GD3gnqnP4Tg.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>The structure of our new all_stats_lines object is a list. Let’s focus now the first element, which will be the column names of our data frame. There are two issues here: 1.) there are three elements that are named ‘avg’ 2.) there is only one element named ‘Player,’ but each player’s name is split between two columns (I’ll fix that later). For now, I’ll focus on changing the column names. I’ll do that by subsetting the first element and the transforming list into a character vector using unlist(). I can assign new values to our column names easily once I transform them back into a character vector.</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/992/1*xYPpGwUda7mddYiidpzS9w.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>The 5th, 15th, and 23rd element of var_lines all are named ‘avg.’ Based on the preceding elements of the vector (and some basketball know-how), we can infer that these elements represent average minutes played, average rebounds, and average points, respectively. I will rename these elements, ‘avg_min’, ‘avg_min’, ‘avg_pts.’</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/994/1*-63krYlE8a2luTya0I6NGA.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>Now that I have finalized my column names, I will focus on rows of the player data.</p>
<figure><img alt="" src="https://i2.wp.com/cdn-images-1.medium.com/max/994/1*sdSqOH2aOZAEfIk8UQ0QFA.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>My next big hurdle is to transform my list of player statistics into a data frame. I will use the ldply() function in the plyr package, which applies a function to each element in a list and combines the results into a data frame.</p>
<figure><img alt="" src="https://i1.wp.com/cdn-images-1.medium.com/max/992/1*van5iWpLWB1FOOKYUfo0SA.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>Now it is time to circle back to the problem of the player names. Remember, the number of column names do not align with the columns of rows of game statistics because each players name is split between two columns (‘V1’ and ‘V2’) in our stats_df object.</p>
<figure><img alt="" src="https://i2.wp.com/cdn-images-1.medium.com/max/990/1*qfg6KOjUY8QFomm1cpDG_A.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>To combine the columns with each players first and last names, I will the unite() function.</p>
<figure><img alt="" src="https://i0.wp.com/cdn-images-1.medium.com/max/993/1*pPmOtuNWsYm3CwKoK6v0Ng.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>Now that our columns finally align, I can finally assemble the final data frame. The first step is to attach the column names using the colnames(). I want to transform my final data frame as a tibble. There are many reasons that working with tibbles can make your life as a data scientist easy (more on that <a rel="nofollow" href="https://cran.r-project.org/web/packages/tibble/vignettes/tibble.html" target="_blank">here</a>). One of which is that tibbles easily handle non-syntactic variable names. To refer to non-syntactic variables, they must be surrounded in backticks.</p>
<p>I am mostly interested in the statistics related to scoring. So, for my final data set I am going to choose specific variables using select(). Because player number and field goal percentage (`fg%`) contain special characters, I have surrounded them in backticks.</p>
<figure><img alt="" src="https://i0.wp.com/cdn-images-1.medium.com/max/995/1*cd3PkGGwQ_B1X69c7v7Ikw.png?w=456&ssl=1" data-recalc-dims="1"></figure>
<p>I now have a clean, tidy final data set ready for analysis, visualization, or export. I hope you learned something new and useful to add to your to your data wrangling toolkit.</p>
<p>Link to the notebook (feel free to copy it): <a rel="nofollow" href="https://www.datazar.com/file/f959f24d7-7f58-4723-88d5-00dd1af63348" target="_blank">https://www.datazar.com/file/f959f24d7-7f58-4723-88d5-00dd1af63348</a></p>
<p>Like what you saw here? Visit <a rel="nofollow" href="http://www.datazar.com/" target="_blank">www.datazar.com</a> to create Notebooks for free and show us what you built @datazarhq.</p>
<p><img width="1" src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f399011549cc" height="1"></p>
<hr>
<p><a rel="nofollow" href="https://blog.datazar.com/extracting-pdf-text-with-r-and-creating-tidy-data-f399011549cc" target="_blank">Extracting PDF Text with R and Creating Tidy Data</a> was originally published in <a rel="nofollow" href="https://blog.datazar.com/" target="_blank">Datazar Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>
	<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/60_sv7u3RbE" height="1">