<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John MacKintosh on Medium]]></title>
        <description><![CDATA[Stories by John MacKintosh on Medium]]></description>
        <link>https://medium.com/@_johnmackintosh?source=rss-38389dea68a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9CIAGBn5gObaIDMQ.png</url>
            <title>Stories by John MacKintosh on Medium</title>
            <link>https://medium.com/@_johnmackintosh?source=rss-38389dea68a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:43:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_johnmackintosh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[R to the Rescue]]></title>
            <link>https://medium.com/@_johnmackintosh/r-to-the-rescue-6887439a8002?source=rss-38389dea68a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6887439a8002</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[John MacKintosh]]></dc:creator>
            <pubDate>Sun, 15 Jan 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-08-24T00:03:33.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was tasked with extracting data from multiple spreadsheets so that it could be included in a report. 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><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*gDy0-cJNgZzpVK3q.gif" /></figure><p><em>the most perfect gif on the planet</em></p><h3>What else could I try?</h3><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? 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><h3>Excel SOS %&gt;% R</h3><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 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>Set up a loop through the current directory (I won’t show that here)</li><li>Create the “SUMMARY” sheet:</li></ul><pre>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</pre><ul><li>Create a named range of appropriate size:</li></ul><pre>createName(wb, name = &quot;Summary&quot;, formula = &quot;SUMMARY!$A$1:$M$8&quot;, overwrite = TRUE)</pre><ul><li>Define friendly column names (e.g. no spaces)</li></ul><pre>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</pre><ul><li>Define a consistent date format:</li></ul><pre>cs &lt;- createCellStyle(wb) setDataFormat(cs, format = &quot;yyyy-mm-dd&quot;)</pre><ul><li>Now populate the date column, starting in cell A2 below the “Date” header:</li></ul><pre># 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</pre><ul><li>Add other columns as required:</li></ul><pre>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;)</pre><ul><li>Add the workbook name and path for troubleshooting:</li></ul><pre>writeWorksheet(wb, n, sheet = &quot;SUMMARY&quot;, startRow = 2, startCol = 20, header = FALSE) saveWorkbook(wb)</pre><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 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 href="http://www.bramschoenmakers.nl/en/node/726">Increase heap size for rJava</a> 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: <a 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. I also began getting out of memory errors again, so I decided on a different approach, abandoning XLConnect in favour of <a href="https://cran.r-project.org/web/packages/readxl/index.html">readXL</a> (for reading the files) and <a href="https://cran.r-project.org/web/packages/data.table/index.html">data.table</a> ( for collating everything together).</p><p><a 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><pre>pathname &lt;- getwd() files&lt;- list.files(pattern = &quot;*.xlsx&quot;) #or use dir() 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) }</pre><p>This was much faster and there were no memory issues. The list was then output to a dataframe per template:</p><pre>mydf1 &lt;-data.table::rbindlist(mylist)</pre><p>Finally all these intermediate dataframes got merged into a new list, then combined to one master dataframe/ data.table:</p><pre>## 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)</pre><p>This probably still looks quite clunky but it worked fine. 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 : <a 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 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 brilliant 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><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*Zpbl9AQhFwcSPWSc.gif" /></figure><p>Thank you to all the brilliant R developers out there who make life easier for the rest of us.</p><p>Tags: rstats, R, r-bloggers</p><p><em>Originally published at </em><a href="http://johnmackintosh.com/2017-01-15-taming-wild-spreadsheets/"><em>johnmackintosh.com</em></a><em> on January 15, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6887439a8002" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hourly heatmap with ggplot2]]></title>
            <link>https://medium.com/@_johnmackintosh/the-hourly-heatmap-with-ggplot2-9e74e344ac9a?source=rss-38389dea68a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e74e344ac9a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[John MacKintosh]]></dc:creator>
            <pubDate>Thu, 01 Dec 2016 00:00:00 GMT</pubDate>
            <atom:updated>2017-08-23T23:56:32.182Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve had a few folk get in touch following my <a href="http://johnmackintosh.com/2016-11-27-calendar-heatmaps/">last post</a>, all commenting on the last plot :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*kkPc2A-ZCXSn9N9F.png" /></figure><p>Most of these enquiries went along the following lines:</p><p>“I hadn’t thought of doing that. It looks really easy. But how do you do it?”</p><p>Unfortunately I was away the last couple of days without access to the code, and I didn’t want to pass on the wrong info. Back home now though, and the code is now uploaded as a gist to GitHub :</p><p><a href="https://gist.github.com/johnmackintosh/520643a1f82a0c7df00cf949ba98a4e9">HeatmapHrbyDay.R</a></p><p>What is the use case? Any organisation/operation that is 24/7 will have some sort of data they can monitor via such a plot. Server loads / web traffic etc could also be analysed this way.</p><p>Some comments :</p><ul><li>The Interpol dataset is pretty large, so we filter out for the first weather station, which conveniently had 2 full years data. We remove all the data we don’t need as we go.</li><li>I use the <a href="https://cran.r-project.org/web/packages/ggExtra/vignettes/ggExtra.html">ggExtra</a> package for easy removal of gridlines (and depending on the plot, easy rotation of axis labels). I know these are not the main functions or reason for the ggExtra package existing, but these commands are easy to remember. Big thanks to <a href="http://deanattali.com/">Dean Attali</a> for all his work on this and other cool R packages. You don’t have to use this package to remove the gridlines, but I will leave you to find the necessary syntax (hint : check my first blog post).</li><li>The beauty and flexibility of ggplot2 is demonstrated once again. The bulk of the plot is produced with these few lines:</li></ul><pre>p &lt;-ggplot(df,aes(day,hour,fill=temp))+ geom_tile(color= &quot;white&quot;,size=0.1) + scale_fill_viridis(name=&quot; Hrly Temps C&quot;,option =&quot;C&quot;) p &lt;-p + facet_grid(year~month)</pre><p>If you type ‘p’ in the console at this point you will see the plot. The rest of the code is formatting tweaks. For more heatmap awesomeness, check out Bob Rudis’s blog:<br> <a href="https://rud.is/projects/facetedheatmaps.html">Bob Rudis faceted heatmaps</a></p><p>I think I’m done with heatmaps for the time being — hope this helped you visualise your data, would love to hear from you if it did.</p><p>Tags: rstats, R, r-bloggers, ggplot2</p><p><em>Originally published at </em><a href="http://johnmackintosh.com/2016-12-01-the-hourly-heatmap/"><em>johnmackintosh.com</em></a><em> on December 1, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e74e344ac9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Daily metric tracking with ggplot2]]></title>
            <link>https://medium.com/@_johnmackintosh/daily-metric-tracking-with-ggplot2-e4b9b85cd30d?source=rss-38389dea68a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b9b85cd30d</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[John MacKintosh]]></dc:creator>
            <pubDate>Sun, 27 Nov 2016 00:00:00 GMT</pubDate>
            <atom:updated>2017-08-23T23:51:47.909Z</atom:updated>
            <content:encoded><![CDATA[<p>In my role I have to produce a lot of run charts and control charts for monthly data, but sometimes there are processes behind the run charts that merit looking at the data on a daily basis.</p><p>It can become impractical to start producing run charts split by day across all metrics (e.g. one for Sunday, one for Monday etc.) so as a quick way of visualising data and spotting patterns for further investigation I’m starting to quite like heatmaps.</p><p>There are a few examples already of calendar style heatmaps in R — specifically Paul Bleicher’s <a href="http://blog.revolutionanalytics.com/2009/11/charting-time-series-as-calendar-heat-maps-in-r.html">CalendarHeat</a> function based on lattice (see link for discussion), and the <a href="https://github.com/Ather-Energy/ggTimeSeries">ggTimeSeries</a> extension which gives us similar functionality within ggplot2.</p><p>Generally, I’ve seen these used for tracking an individual metric over an extended time period (e.g. a year or more). I have never got to grips with the lattice system, so I decided to have a bash at producing some thing loosely based on these but using ggplot2 instead.</p><p>I had 2 aims:</p><ul><li>I wanted something that would allow me to visualise data for a larger number of metrics, but over a much smaller time period</li><li>It was absolutely not to be a run chart or some other line plot (in my defence, I’ve produced 1000’s of these already and will be producing many more in the future)</li></ul><p>Before we go on please bear in mind this is <em>randomly generated</em> data (<em>from the future!</em>) — so it is very much pot luck as to how effective these look. The aim was to have a mix of high, mid and low frequency variables to mirror typical metrics within most organisations:</p><h3>All metrics, month at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LWQjN7AjY0sTxEkG.png" /></figure><p>This gives a nice overview of a dozen metrics, per day, for a given month, in this case, Dec 2016 — which, at the time of writing, hasn’t happened yet (I did say this was made up didn’t I?)</p><p>The first question that arises — to label, or not? Generally heatmaps aren’t labelled, and I like the purity of the above plot, but unless it’s made available as an interactive plot , the audience has no way to accurately determine the values.</p><p>Speaking of interactive, here is how this would look using plotly within R:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Fbec4O-YIuzFzMuR.png" /></figure><p>Plotly is really nice, but I can see that people may not want to be hovering over each tile to determine the value, especially if its a plot type that is new to them.</p><p>So, bearing in mind I generally have to export plots as static images, here is a labelled version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9JOCo3oS8ekMZft0.png" /></figure><p>Here I overlaid labels with geom_text , after creating separate dataframes to control the text colour - depending on the values within the data you may have to play around with this.</p><p>One criticism of these is that the 0 values are filled and so it becomes difficult to determine much variance between these and the other values for metrics A-C.</p><p>A way round that is to rescale each metric individually to a value between 0 and 1, to standardise the variance in the fill shades across metrics. You then use the rescaled value as the basis for plotting — and overlay with the labels as before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9c9dszy5McHbGx_S.png" /></figure><h3>Calendar style view by metric</h3><p>If you want to look at patterns by weekday, both individually and across all the metrics, then this layout can work well. First, here’s the labelled, unscaled version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*GHszsw7qWcYqW-NB.png" /></figure><p>Here is the rescaled version, for comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*c1BUDtg13hg1hpi2.png" /></figure><p>Bearing in mind this is entirely randomly generated data, you can still see some patterns here for some metrics. If you try something similar with your own data you may find something that was previously “non-obvious” now stands out. Then you can delve deeper if there is specific day or sequence that catches your attention.</p><h3>Lose the zeros</h3><p>This speaks for itself, here is the first plot again but this time I stripped out the zero values so they did not get filled in with the same palette as the other values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*AZiKuKWVZ7vxYXib.png" /></figure><p>You may have to denote that white = 0, or it may be assumed that these are missing values instead. Again, the best approach depends on the data and your audience.</p><p>Heatmaps may not be everyone’s cup of tea. You could use more robust methods to determine whether 2 or more metrics increase together or not. There are also better ways of visualising these relationships, like the awesome looking <a href="https://drsimonj.svbtle.com/explore-correlations-in-r-with-corrr">corrr</a> package.</p><p>That said, I still like heatmaps as a quick way to visualise high volume/high frequency data underlying some of the high level metrics that I routinely measure. You don’t know what previously unseen patterns may emerge, so there is nothing to lose by plotting them. I also find that people who may not be huge fans of charts (there are some strange folk who prefer tables), actually <em>do</em> like heatmaps. Again, once people get engaged then you can move on to other visualisations in due course.</p><p>I’m going to finish off with a plot I produced earlier in the year, for a talk I did on ggplot2. This shows data by hour, day, month and year. Its based on a very old dataset from the Interpol.T library - I wanted something that would allow me to plot hourly data by day and I have used similar plots with real-life data as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*aZ4ALvXdPh_j1xvC.png" /></figure><p>It looks better on screen, it has to be said — it got a bit squished during the export process — but you get the idea. I’ve been trying to recreate something like this with QlikView and that is still very much a work in progress, whereas ggplot2 and lubridate make it easier to take an idea and see it through to reality.</p><p>That’s all for this post, hope you liked this and hope it has sparked some ideas for taking an alternative look at your data.</p><p>Tags: rstats, R, r-bloggers</p><p><em>Originally published at </em><a href="http://johnmackintosh.com/2016-11-27-calendar-heatmaps/"><em>johnmackintosh.com</em></a><em> on November 27, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b9b85cd30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>