<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>OUseful.Info, the blog... &#187; Power Tools for Aspiring Data Journalists: Funnel Plots in R</title>
	<atom:link href="http://blog.ouseful.info/2011/10/31/power-tools-for-aspiring-data-journalists-r/feed/?withoutcomments=1" rel="self" type="application/rss+xml" />
	<link>http://blog.ouseful.info</link>
	<description>Trying to find useful things to do with emerging technologies in open education</description>
	<lastBuildDate>Tue, 21 May 2013 14:35:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.ouseful.info' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>OUseful.Info, the blog... &#187; Power Tools for Aspiring Data Journalists: Funnel Plots in R</title>
		<link>http://blog.ouseful.info</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.ouseful.info/osd.xml" title="OUseful.Info, the blog..." />
	<atom:link rel='hub' href='http://blog.ouseful.info/?pushpress=hub'/>
		<item>
		<title>Power Tools for Aspiring Data Journalists: Funnel Plots in R</title>
		<link>http://blog.ouseful.info/2011/10/31/power-tools-for-aspiring-data-journalists-r/</link>
		<comments>http://blog.ouseful.info/2011/10/31/power-tools-for-aspiring-data-journalists-r/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 13:32:50 +0000</pubDate>
		<dc:creator>Tony Hirst</dc:creator>
				<category><![CDATA[Data]]></category>
		<category><![CDATA[Infoskills]]></category>
		<category><![CDATA[onlinejournalismblog]]></category>
		<category><![CDATA[Rstats]]></category>
		<category><![CDATA[funnel plot]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[replication]]></category>
		<category><![CDATA[stats]]></category>

		<guid isPermaLink="false">http://blog.ouseful.info/?p=6361</guid>
		<description><![CDATA[Picking up on Paul Bradshaw&#8217;s post A quick exercise for aspiring data journalists which hints at how you can use Google Spreadsheets to grab &#8211; and explore &#8211; a mortality dataset highlighted by Ben Goldacre in DIY statistical analysis: experience the thrill of touching real data, I thought I&#8217;d describe a quick way of analysing [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.ouseful.info&#038;blog=325417&#038;post=6361&#038;subd=ouseful&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Picking up on Paul Bradshaw&#8217;s post <a href="http://onlinejournalismblog.com/2011/10/31/a-quick-exercise-for-aspiring-data-journalists/">A quick exercise for aspiring data journalists</a> which hints at how you can use Google Spreadsheets to grab &#8211; and explore &#8211; a mortality dataset highlighted by Ben Goldacre in <a href="http://www.guardian.co.uk/commentisfree/2011/oct/28/bad-science-diy-data-analysis">DIY statistical analysis: experience the thrill of touching real data</a>, I thought I&#8217;d describe a quick way of analysing the data using R, a very powerful statistical programming environment that should probably be part of your toolkit if you ever want to get round to doing some serious stats, and have a go at reproducing the analysis using a bit of judicious websearching and some cut-and-paste action&#8230;</p>
<p>R is an open-source, cross-platform environment that allows you to do programming like things with stats, as well as producing a wide range of graphical statistics (stats visualisations) as if by magic. (Which is to say, it can be terrifying to try to get your head round&#8230; but once you&#8217;ve grasped a few key concepts, it becomes a really powerful tool&#8230; At least, that&#8217;s what I&#8217;m hoping as I struggle to learn how to use it myself!) </p>
<p>I&#8217;ve been using <a href="http://rstudio.org">R-Studio</a> to work with R, a) because it&#8217;s free and works cross-platform, b) it can be run as a service and accessed via the web (though I haven&#8217;t tried that yet; the hosted option still hasn&#8217;t appeared yet, either&#8230;), and c) it offers a structured environment for managing R projects.</p>
<p>So, to get started. Paul describes a dataset posted as an HTML table by Ben Goldacre that is used to generate the dots on this graph:</p>
<p><img alt="" src="http://static.guim.co.uk/sys-images/Admin/BkFill/Default_image_group/2011/10/28/1319816474482/bowel-cancer-mortality-ra-007.jpg" title="Bowel Cancer Mortality Rates" class="alignnone" width="460" height="276" /></p>
<p>The lines come from a probabilistic model that helps us see the likely spread of death rates given a particular population size.</p>
<p>If we want to do stats on the data, then we could, as Paul suggests, pull the data into a spreadsheet and then work from there&#8230; Or, we could pull it directly into R, at which point all manner of voodoo stats capabilities become available to us.</p>
<p>As with the <em>=importHTML</em> formula in Google spreadsheets, R has a way of scraping data from an HTML table anywhere on the public web:</p>
<p><tt>#First, we need to load in the XML library that contains the scraper function<br />
library(XML)<br />
#Scrape the table<br />
cancerdata=data.frame( readHTMLTable( 'http://www.guardian.co.uk/commentisfree/2011/oct/28/bad-science-diy-data-analysis', which=1, header=c('Area','Rate','Population','Number')))</tt></p>
<p>The format is simple: <tt>readHTMLTable(url,which=TABLENUMBER)</tt> (TABLENUMBER is used to extract the N&#8217;th table in the page.) The <tt>header</tt> part labels the columns (the data pulled in from the HTML table itself contains all sorts of clutter).</p>
<p>We can inspect the data we&#8217;ve imported as follows:</p>
<p><tt>#Look at the whole table<br />
cancerdata<br />
#Look at the column headers<br />
names(cancerdata)<br />
#Look at the first 10 rows<br />
head(cancerdata)<br />
#Look at the last 10 rows<br />
tail(cancerdata)<br />
#What sort of datatype is in the Number column?<br />
class(cancerdata$Number)<br />
</tt></p>
<p>The last line &#8211; <tt>class(cancerdata$Number)</tt> &#8211; identifies the data as type &#8216;factor&#8217;. In order to do stats and plot graphs, we need the Number, Rate and Population columns to contain actual numbers&#8230; (Factors organise data according to categories; when the table is loaded in, the data is loaded in as strings of characters; rather than seeing each number as a number, it&#8217;s identified as a category.)</p>
<p><tt>#Convert the numerical columns to a numeric datatype<br />
cancerdata$Rate=as.numeric(levels(cancerdata$Rate)[as.integer(cancerdata$Rate)])<br />
cancerdata$Population=as.numeric(levels(cancerdata$Population)[as.integer(cancerdata$Population)])<br />
cancerdata$Number=as.numeric(levels(cancerdata$Number)[as.integer(cancerdata$Number)])</tt><br />
#Just check it worked&#8230;<br />
class(cancerdata$Number)<br />
head(cancerdata)<br />
</tt></p>
<p>We can now plot the data:</p>
<p><tt>#Plot the Number of deaths by the Population<br />
plot(Number ~ Population,data=cancerdata)</tt></p>
<p>If we want to, we can add a title:<br />
<tt>#Add a title to the plot<br />
plot(Number ~ Population,data=cancerdata, main='Bowel Cancer Occurrence by Population')</tt></p>
<p>We can also tweak the axis labels:</p>
<p><tt>plot(Number ~ Population,data=cancerdata, main='Bowel Cancer Occurrence by Population',ylab='Number of deaths')</tt></p>
<p><a href="http://ouseful.files.wordpress.com/2011/10/cancerdatasimple.png"><img src="http://ouseful.files.wordpress.com/2011/10/cancerdatasimple.png?w=700" alt="" title="cancerdataSimple"   class="alignnone size-full wp-image-6364" /></a></p>
<p>The <tt>plot</tt> command is great for generating quick charts. If we want a bit more control over the charts we produce, the <em>ggplot2</em> library is the way to go. (<em>ggpplot2</em> isn't part of the standard R bundle, so you'll need to install the package yourself if you haven't already installed it. In RStudio, find the <em>Packages</em> tab, click <em>Install Packages</em>, search for <em>ggplot2</em> and then install it, along with its dependencies...):</p>
<p><tt>require(ggplot2)<br />
ggplot(cancerdata)+geom_point(aes(x=Population,y=Number))+opts(title='Bowel Cancer Data')+ylab('Number of Deaths')</tt></p>
<p><a href="http://ouseful.files.wordpress.com/2011/10/cancerdata_ggplot.png"><img src="http://ouseful.files.wordpress.com/2011/10/cancerdata_ggplot.png?w=700" alt="" title="cancerdata_ggplot"   class="alignnone size-full wp-image-6365" /></a></p>
<p>Doing a bit of searching for the "funnel plot" chart type used to display the ata in Goldacre's article, I came across a post on Cross Validated, the Stack Overflow/Statck Exchange site dedicated to statistics related Q&amp;A: <a href="http://stats.stackexchange.com/questions/5195/how-to-draw-funnel-plot-using-ggplot2-in-r">How to draw funnel plot using ggplot2 in R?</a></p>
<p>The meta-analysis answer seemed to produce the similar chart type, so I had a go at cribbing the code... This is a dangerous thing to do, and I can't guarantee that the analysis is the same type of analysis as the one Goldacre refers to... but what I'm trying to do is show (quickly) that R provides a very powerful stats analysis environment and could probably do the sort of analysis you want in the hands of someone who knows how to drive it, and also knows what stats methods can be appropriately applied for any given data set...</p>
<p>Anyway - here's something resembling the Goldacre plot, using the cribbed code which has confidence limits at the 95% and 99.9% levels. Note that I needed to do a couple of things:</p>
<p>1) work out what values to use where! I did this by looking at the ggplot code to see what was plotted. p was on the y-axis and should be used to present the death rate. The data provides this as a rate per 100,000, so we need to divide by 100, 000 to make it a rate in the range 0..1. The x-axis is the population.</p>
<p><tt>#TH: funnel plot code from:<br />
#TH: <a href="http://stats.stackexchange.com/questions/5195/how-to-draw-funnel-plot-using-ggplot2-in-r/5210#5210" rel="nofollow">http://stats.stackexchange.com/questions/5195/how-to-draw-funnel-plot-using-ggplot2-in-r/5210#5210</a><br />
#TH: Use our cancerdata<br />
number=cancerdata$Population<br />
#TH: The rate is given as a 'per 100,000' value, so normalise it<br />
p=cancerdata$Rate/100000</p>
<p>p.se &lt;- sqrt((p*(1-p)) / (number))<br />
df &lt;- data.frame(p, number, p.se)</p>
<p>## common effect (fixed effect model)<br />
p.fem &lt;- weighted.mean(p, 1/p.se^2)</p>
<p>## lower and upper limits for 95% and 99.9% CI, based on FEM estimator<br />
#TH: I&#039;m going to alter the spacing of the samples used to generate the curves<br />
number.seq &lt;- seq(1000, max(number), 1000)<br />
number.ll95 &lt;- p.fem - 1.96 * sqrt((p.fem*(1-p.fem)) / (number.seq))<br />
number.ul95 &lt;- p.fem + 1.96 * sqrt((p.fem*(1-p.fem)) / (number.seq))<br />
number.ll999 &lt;- p.fem - 3.29 * sqrt((p.fem*(1-p.fem)) / (number.seq))<br />
number.ul999 &lt;- p.fem + 3.29 * sqrt((p.fem*(1-p.fem)) / (number.seq))<br />
dfCI &lt;- data.frame(number.ll95, number.ul95, number.ll999, number.ul999, number.seq, p.fem)</p>
<p>## draw plot<br />
#TH: note that we need to tweak the limits of the y-axis<br />
fp &lt;- ggplot(aes(x = number, y = p), data = df) +<br />
    geom_point(shape = 1) +<br />
    geom_line(aes(x = number.seq, y = number.ll95), data = dfCI) +<br />
    geom_line(aes(x = number.seq, y = number.ul95), data = dfCI) +<br />
    geom_line(aes(x = number.seq, y = number.ll999, linetype = 2), data = dfCI) +<br />
    geom_line(aes(x = number.seq, y = number.ul999, linetype = 2), data = dfCI) +<br />
    geom_hline(aes(yintercept = p.fem), data = dfCI) +<br />
    scale_y_continuous(limits = c(0,0.0004)) +<br />
  xlab(&quot;number&quot;) + ylab(&quot;p&quot;) + theme_bw() </p>
<p>fp</tt></p>
<p><a href="http://ouseful.files.wordpress.com/2011/10/cancerdatafunnelplot.png"><img src="http://ouseful.files.wordpress.com/2011/10/cancerdatafunnelplot.png?w=700" alt="" title="cancerdataFunnelplot"   class="alignnone size-full wp-image-6367" /></a></p>
<p>As I said above, it can be quite dangerous just pinching other folks' stats code if you aren't a statistician and don't really know whether you have actually replicated someone else's analysis or done something completely different... (this is a situation I often find myself in!); which is why I think we need to encourage folk who release statistical reports to not only release their data, but also show their working, including the code they used to generate any summary tables or charts that appear in those reports.</p>
<p>In addition, it's worth noting that cribbing other folk's code and analyses and applying it to your own data may lead to a nonsense result because some stats analyses only work if the data has the right sort of distribution...So be aware of that, always post your own working somewhere, and if someone then points out that it's nonsense, you'll hopefully be able to learn from it...</p>
<p>Given those caveats, what I hope to have done is raise awareness of what R can be used to do (including pulling data into a stats computing environment via an HTML table screenscrape) and also produced some sort of recipe we could take to a statistician to say: is this the sort of thing Ben Goldacre was talking about? And if not, why not?</p>
<p>[If I've made any huge - or even minor - blunders in the above, please let me know... There's always a risk in cutting and pasting things that look like they produce the sort of thing you're interested in, but may actually be doing something completely different!]</p>
<p>PS for how to generate reports that can (optionally) also self-document with actually source R code, see <a href="http://blog.ouseful.info/2011/11/01/how-might-data-journalists-show-their-working-sweave/">How might data journalists show their working? Sweave</a>. The code used in, and comments added to, that post make further refinements to the funnel plot code.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ouseful.wordpress.com/6361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ouseful.wordpress.com/6361/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.ouseful.info&#038;blog=325417&#038;post=6361&#038;subd=ouseful&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.ouseful.info/2011/10/31/power-tools-for-aspiring-data-journalists-r/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abbd9f90565ce9ae4d065d93a81d8c03?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Tony Hirst</media:title>
		</media:content>

		<media:content url="http://static.guim.co.uk/sys-images/Admin/BkFill/Default_image_group/2011/10/28/1319816474482/bowel-cancer-mortality-ra-007.jpg" medium="image">
			<media:title type="html">Bowel Cancer Mortality Rates</media:title>
		</media:content>

		<media:content url="http://ouseful.files.wordpress.com/2011/10/cancerdatasimple.png" medium="image">
			<media:title type="html">cancerdataSimple</media:title>
		</media:content>

		<media:content url="http://ouseful.files.wordpress.com/2011/10/cancerdata_ggplot.png" medium="image">
			<media:title type="html">cancerdata_ggplot</media:title>
		</media:content>

		<media:content url="http://ouseful.files.wordpress.com/2011/10/cancerdatafunnelplot.png" medium="image">
			<media:title type="html">cancerdataFunnelplot</media:title>
		</media:content>
	</item>
	</channel>
</rss>
