<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/r-to-the-rescue/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://johnmackintosh.com/2017-01-15-taming-wild-spreadsheets/"> HighlandR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>	A strategy for gathering scattered spreadsheet data with R – </p>
<h2>A simple request</h2>
<p>Recently I was tasked with extracting data from multiple spreadsheets so that it could be included in a report.<br>
Seemed like a fairly innocuous request, but it turned out to be a bit more challenging.</p>
<p>I had over 140 files to process. That’s not usually a big deal – I normally use SQL Server Integration Services to loop through network folders, connect to hundreds of spreadsheets and extract the source data.</p>
<p><strong>But</strong> this relies on the data being in a tabular format (like a dataframe or database table).</p>
<p>A quick glance at the first few sheets confirmed I could not use this approach – the data was not in tabular format. Instead it was laid out in a format suited to viewing the data on screen – with the required data scattered in different ranges throughout each sheet ( over 100 rows and many columns). It wasn’t going to be feasible to point SSIS at different locations within each sheet. (It can be done, but it’s pretty complex and I didn’t have time to experiment).</p>
<p>The other challenge was that over time, changes to design meant that data moved location e.g. dates that were originally in cell C2 moved to D7, then moved again as requirements evolved. There were 14 different templates in all, each with subtle changes. Each template was going to need a custom solution to extract the data.</p>
<p><img alt="" src="https://i2.wp.com/i.giphy.com/SEp6Zq6ZkzUNW.gif?w=456" data-recalc-dims="1"></p>
<p><em>the most perfect gif on the planet</em></p>
<h2>What else could I try?</h2>
<p>I need to create a consistent, tabular summary in each workbook – referencing the relevant cells in each sheet. This would give me 8 rows ( 1 header row, plus 1 each day for Mon-Sun) with as many columns as required (1 for each metric), that I could then import via SSIS.</p>
<p>But – how to write the formulae in this summary sheet?<br>
I could easily do this manually, but then was I going to copy and paste the formulae to the remaining workbooks? The formulae would need amending each time to remove the external references. One false move and there’d be an infernal loop of broken references that Excel couldn’t navigate. No – this was not going to be the answer.</p>
<p>How about VBA? I’ve used that in the past (before SSIS) to loop through hundreds of XLS files and collating to a master workbook – but the looping could be quite slow and could be difficult to trouble shoot. It had also been a while since I wrote any VBA and I didn’t have much time to get myself back into a VBA mindset.</p>
<p>Thinking ahead, once I’d created these summary sheets, and collated them, I was going to need to analyse and visualise the data. I needed a tool that could write to Excel, collate the data, perform analysis and visualise many metrics at once. I also needed the solution to be reproducible, in case of errors. And I needed to produce multiple visualisations without having to manually create each plot.</p>
<h2>Excel SOS %>% R</h2>
<p>I already had R in mind as a potential solution, so had spent some time earlier looking into packages that could both read and write to Excel. I chose <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/XLConnect/index.html">XLConnect</a>. It has a simple syntax, which, given the time pressure I was under, was very welcome.</p>
<p>I won’t show the exact code I used, but can give a general idea of my approach:</p>
<ul>
<li>
<p>Set up a loop through the current directory (I won’t show that here)</p>
</li>
<li>
<p>Create the “SUMMARY” sheet:</p>
</li>
</ul>
<div>
<pre><code>removeSheet(wb,&quot;SUMMARY&quot;) 
createSheet(wb, name = &quot;SUMMARY&quot;) 
# delete the summary sheet (in case of having to re-run the code due to errors) and recreate
</code></pre>
</div>
<ul>
<li>Create a named range of appropriate size:</li>
</ul>
<div>
<pre><code>createName(wb, name = &quot;Summary&quot;, formula = &quot;SUMMARY!$A$1:$M$8&quot;, overwrite = TRUE) 	
</code></pre>
</div>
<ul>
<li>Define friendly column names (e.g. no spaces)</li>
</ul>
<div>
<pre><code>Headers &lt;- data.frame(&quot;Header1&quot;,&quot;Header2&quot;)# for as many cols as you need
writeWorksheet(wb, Headers, sheet = &quot;SUMMARY&quot;, startRow = 1, startCol = 1, header = FALSE)
# Write the headers to the range beginning A1. 
# Use header =  FALSE to stop default column headers being written, we want OUR newly defined column headers
</code></pre>
</div>
<ul>
<li>Define a consistent date format:</li>
</ul>
<div>
<pre><code>cs &lt;- createCellStyle(wb)
setDataFormat(cs, format = &quot;yyyy-mm-dd&quot;)
</code></pre>
</div>
<ul>
<li>Now populate the date column, starting in cell A2 below the “Date” header:</li>
</ul>
<div>
<pre><code># insert dates into A2 on SUMMARY sheet
setCellFormula(wb,&quot;SUMMARY&quot;,2,1,formula = &quot;Sheet1!$C$5&quot;) # reference the date from Sheet1, cell C5 
setCellStyle(wb, sheet = &quot;SUMMARY&quot;, row = 2, col = 1, cellstyle = cs)# now format as date on Summary sheet
# repeat for the remaining days
</code></pre>
</div>
<ul>
<li>Add other columns as required:</li>
</ul>
<div>
<pre><code>setCellFormula(wb,S,2,4,formula = &quot;Sheet1!$J$20&quot;)
setCellFormula(wb,S,3,4,formula = &quot;Sheet2!$J$20&quot;)
setCellFormula(wb,S,4,4,formula = &quot;Sheet3!$J$20&quot;)
setCellFormula(wb,S,5,4,formula = &quot;Sheet4!$J$20&quot;)
setCellFormula(wb,S,6,4,formula = &quot;Sheet5!$J$20&quot;)
setCellFormula(wb,S,7,4,formula = &quot;Sheet6!$J$20&quot;)
setCellFormula(wb,S,8,4,formula = &quot;Sheet7!$J$20&quot;)

# In real life the sheets had different names 
# e.g. if your was called &quot;Expenses&quot; then the reference might be :
setCellFormula(wb,S,8,4,formula = &quot;Expenses!$B$10&quot;)
</code></pre>
</div>
<ul>
<li>Add the workbook name and path for troubleshooting:</li>
</ul>
<div>
<pre><code>writeWorksheet(wb, n, sheet = &quot;SUMMARY&quot;, startRow = 2, startCol = 20, header = FALSE)

saveWorkbook(wb)
</code></pre>
</div>
<h3>Problems I encountered</h3>
<ul>
<li>The Summary sheet not showing properly in the file browser preview window. Not sure if this was a Windows or Excel (2010) issue, but browsing a few of the spreadsheets in preview mode to test the code showed the “SUMMARY” sheet had been created, but I couldn’t see anything in the sheet itself – it looked completely blank.</li>
</ul>
<p>It wasn’t until I eventually opened the workbook and saw the summary sheet with the populated references that I knew my approach had worked. The rest of the workbook was completely visible via the preview window, so not sure why the contents of this new sheet weren’t? This certainly threw me for a bit – I was double checking my code and couldn’t see why it wasn’t working.</p>
<ul>
<li>Out of memory errors. I couldn’t process more than few files at a time before my laptop began to hang – and then cryptic warnings appeared about heap space errors.</li>
</ul>
<p>Here are the links you’ll need if it happens to you:</p>
<p><a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/7963393/out-of-memory-error-java-when-using-r-and-xlconnect-package">out-of-memory-error-java-when-using-r-and-xlconnect-package</a><br>
The second answer helped me.</p>
<p><a target="_blank" rel="nofollow" href="http://www.bramschoenmakers.nl/en/node/726">Increase heap size for rJava</a><br>
This is referenced from the SO link and gives more info on what to do.</p>
<p>Ultimately I got round this by creating several more sub-directories, and ensuring I never had more than 4 or 5 files in each. This may or may not work for you, depending on the files you are manipulating, and computer specs. (My laptop has 8MB RAM and handles virtually everything else I throw at it).</p>
<h3>Pulling it all together</h3>
<p>Once the code worked for the first template, it was a matter of working through the other dozen or so and amending the code to reference the correct cells. Lots of Find/Replace ( a lot easier in RStudio, thankfully).</p>
<p>I was wondering afterwards if I should have attempted to create a set of functions, but I’d have had to amend the cell references anyway each time anyway, so I’m not sure it would have benefitted.</p>
<p>The final challenge was collating all the summary sheets, from all the files, into 1 main file.</p>
<p>This is not a task I’ve had to do before with R so at this point, I deferred to the geniuses at Stack Overflow:<br>
<a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/22394234/loop-for-read-and-merge-multiple-excel-sheets-in-r">loop-for-read-and-merge-multiple-excel-sheets-in-r</a></p>
<p>This helped, but turned out to be quite cumbersome as the number of files racked up.<br>
I also began getting out of memory errors again, so I decided on a different approach, abandoning XLConnect in favour of <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/readxl/index.html">readXL</a> (for reading the files) and <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/data.table/index.html">data.table</a> ( for collating everything together).</p>
<p><a target="_blank" rel="nofollow" href="https://itsalocke.com/r-quick-tip-collapse-a-lists-of-data-frames-with-data-table/">This post</a> by Steff Locke gave me the push towards data table, the first example worked fine for me as thankfully all the sheets were now consistent.</p>
<p>Basically, all the individual summary sheets got read in as a dataframe, and each was added to a list in turn:</p>
<div>
<pre><code>pathname &lt;- getwd()
files&lt;- list.files(pattern = &quot;*.xlsx&quot;) #or use dir()
filecount&lt;-as.numeric(length(files))  # for sizing the loop

mylist &lt;- list()

for (i in seq_along(files)){
filename&lt;-files[i] 
df&lt;-read_excel(path=filename, sheet = &quot;SUMMARY&quot;, 
               col_names = TRUE, col_types = NULL, 
               na = &quot;&quot;, skip = 0)
mylist[[i]]&lt;-df
rm(df)
}  
</code></pre>
</div>
<p>This was much faster and there were no memory issues.  The list was then output to a dataframe per template:</p>
<div>
<pre><code>mydf1 &lt;-data.table::rbindlist(mylist)

</code></pre>
</div>
<p>Finally all these intermediate dataframes got merged into a new list, then combined to one master dataframe/ data.table:</p>
<div>
<pre><code>## merge all the dfs
l.df &lt;- lapply(ls(), function(x) if (class(get(x)) == &quot;data.table&quot;) get(x))
#http://stackoverflow.com/questions/14954399/put-multiple-data-frames-into-list-smart-way
# I set class to data.table as that is first in list and data.frame was being ignored
maindf&lt;-data.table::rbindlist(l.df)  

</code></pre>
</div>
<p>This probably still looks quite clunky but it worked fine.<br>
I had one master dataframe which I then set to work on with dplyr.</p>
<p>I could have moved all the files to one directory, and looped through them all at once. But I left them in case I had to repeat the process – I did not want the out of memory errors to reoccur. It was straighforward to import the data via SSIS at this stage, but the advantage of doing so in R meant I could move straight on to exploring the data.</p>
<p>Is this the best approach? Well it worked… and I was not aware of anything else that would do the job at the time.</p>
<p>A couple of months later I saw this presentation by Jenny Bryan :<br>
<a target="_blank" rel="nofollow" href="https://channel9.msdn.com/Events/useR-international-R-User-conference/useR2016/jailbreakr-Get-out-of-Excel-free">Jailbreakr-Get-out-of-Excel-free</a>.</p>
<p>This refers to jailbreakr – the github repo is here : <a target="_blank" rel="nofollow" href="https://github.com/rsheets/jailbreakr">https://github.com/rsheets/jailbreakr</a> and it seeks to address the same problem.</p>
<p>The purpose is :</p>
<p><strong>Data Liberator. To extract tabular data people put in nontabular structures in a program designed to hold tables.</strong></p>
<p>It’s still in the early stages though so I couldn’t have used it, even if i’d been aware of it – but it’s certainly one to keep an eye on. Especially because of the awesome gifs (including the awesome one above).</p>
<p>At least until such time as jailbreakr is available I have a proven strategy for dealing with spreadsheet chaos. So next time this situation occurs I can be more serene :</p>
<p><img alt="" src="https://i1.wp.com/i.giphy.com/99e1L4KIXQh6U.gif?w=456" data-recalc-dims="1"></p>
<p>Thank you to all the brilliant R developers out there who make life easier for the rest of us.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://johnmackintosh.com/2017-01-15-taming-wild-spreadsheets/"> HighlandR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/NcQeb4Et9mU"></a></div>