-
Notifications
You must be signed in to change notification settings - Fork 16
/
Outlier-Treatment-With-R.html
395 lines (359 loc) · 31.7 KB
/
Outlier-Treatment-With-R.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<!DOCTYPE html>
<html>
<head>
<title>Outlier Treatment With R | Multivariate Outliers</title>
<meta charset="utf-8">
<meta name="Description" content="R Language Tutorials for Advanced Statistics">
<meta name="Keywords" content="R, Tutorial, Machine learning, Statistics, Data Mining, Analytics, Data science, Linear Regression, Logistic Regression, Time series, Forecasting">
<meta name="Distribution" content="Global">
<meta name="Author" content="Selva Prabhakaran">
<meta name="Robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/screenshots/iconb-64.png" type="image/x-icon" />
<link href="www/bootstrap.min.css" rel="stylesheet">
<link href="www/highlight.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Inconsolata:400,700'
rel='stylesheet' type='text/css'>
<!-- Color Script -->
<style type="text/css">
a {
color: #3675C5;
color: rgb(25, 145, 248);
color: #4582ec;
color: #3F73D8;
}
li {
line-height: 1.65;
}
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
</style>
<!-- Add Google search -->
<script language="Javascript" type="text/javascript">
function my_search_google()
{
var query = document.getElementById("my-google-search").value;
window.open("http://google.com/search?q=" + query
+ "%20site:" + "http://r-statistics.co");
}
</script>
</head>
<body>
<div class="container">
<div class="masthead">
<!--
<ul class="nav nav-pills pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Table of contents<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</ul>
-->
<ul class="nav nav-pills pull-right">
<div class="input-group">
<form onsubmit="my_search_google()">
<input type="text" class="form-control" id="my-google-search" placeholder="Search..">
<form>
</div><!-- /input-group -->
</ul><!-- /.col-lg-6 -->
<h3 class="muted"><a href="/">r-statistics.co</a><small> by Selva Prabhakaran</small></h3>
<hr>
</div>
<div class="row">
<div class="col-xs-12 col-sm-3" id="nav">
<div class="well">
<li>
<ul class="list-unstyled">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</div>
<div class="well">
<p>Stay up-to-date. <a href="https://docs.google.com/forms/d/1xkMYkLNFU9U39Dd8S_2JC0p8B5t6_Yq6zUQjanQQJpY/viewform">Subscribe!</a></p>
<p><a href="https://docs.google.com/forms/d/13GrkCFcNa-TOIllQghsz2SIEbc-YqY9eJX02B19l5Ow/viewform">Chat!</a></p>
</div>
<h4>Contents</h4>
<ul class="list-unstyled" id="toc"></ul>
<!--
<hr>
<p><a href="/contribute.html">How to contribute</a></p>
<p><a class="btn btn-primary" href="">Edit this page</a></p>
-->
</div>
<div id="content" class="col-xs-12 col-sm-8 pull-right">
<h1>Outlier Treatment</h1>
<blockquote>
<p>Outliers in data can distort predictions and affect the accuracy, if you don’t detect and handle them appropriately especially in regression models.</p>
</blockquote>
<h2>Why outliers detection is important?</h2>
<p>Treating or altering the outlier/extreme values in genuine observations is not a standard operating procedure. However, it is essential to understand their impact on your predictive models. It is left to the best judgement of the investigator to decide whether treating outliers is necessary and how to go about it.</p>
<p>So, why identifying the extreme values is important? Because, it can drastically bias/change the fit estimates and predictions. Let me illustrate this using the cars dataset.</p>
<p>To better understand the implications of outliers better, I am going to compare the fit of a simple linear regression model on cars dataset <em>with</em> and <em>without</em> outliers. In order to distinguish the effect clearly, I manually introduce extreme values to the original cars dataset. Then, I predict on both the datasets.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Inject outliers into data.</span>
cars1 <-<span class="st"> </span>cars[<span class="dv">1</span>:<span class="dv">30</span>, ] <span class="co"># original data</span>
cars_outliers <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">speed=</span><span class="kw">c</span>(<span class="dv">19</span>,<span class="dv">19</span>,<span class="dv">20</span>,<span class="dv">20</span>,<span class="dv">20</span>), <span class="dt">dist=</span><span class="kw">c</span>(<span class="dv">190</span>, <span class="dv">186</span>, <span class="dv">210</span>, <span class="dv">220</span>, <span class="dv">218</span>)) <span class="co"># introduce outliers.</span>
cars2 <-<span class="st"> </span><span class="kw">rbind</span>(cars1, cars_outliers) <span class="co"># data with outliers.</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Plot of data with outliers.</span>
<span class="kw">par</span>(<span class="dt">mfrow=</span><span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">2</span>))
<span class="kw">plot</span>(cars2$speed, cars2$dist, <span class="dt">xlim=</span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">28</span>), <span class="dt">ylim=</span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">230</span>), <span class="dt">main=</span><span class="st">"With Outliers"</span>, <span class="dt">xlab=</span><span class="st">"speed"</span>, <span class="dt">ylab=</span><span class="st">"dist"</span>, <span class="dt">pch=</span><span class="st">"*"</span>, <span class="dt">col=</span><span class="st">"red"</span>, <span class="dt">cex=</span><span class="dv">2</span>)
<span class="kw">abline</span>(<span class="kw">lm</span>(dist ~<span class="st"> </span>speed, <span class="dt">data=</span>cars2), <span class="dt">col=</span><span class="st">"blue"</span>, <span class="dt">lwd=</span><span class="dv">3</span>, <span class="dt">lty=</span><span class="dv">2</span>)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Plot of original data without outliers. Note the change in slope (angle) of best fit line.</span>
<span class="kw">plot</span>(cars1$speed, cars1$dist, <span class="dt">xlim=</span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">28</span>), <span class="dt">ylim=</span><span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">230</span>), <span class="dt">main=</span><span class="st">"Outliers removed </span><span class="ch">\n</span><span class="st"> A much better fit!"</span>, <span class="dt">xlab=</span><span class="st">"speed"</span>, <span class="dt">ylab=</span><span class="st">"dist"</span>, <span class="dt">pch=</span><span class="st">"*"</span>, <span class="dt">col=</span><span class="st">"red"</span>, <span class="dt">cex=</span><span class="dv">2</span>)
<span class="kw">abline</span>(<span class="kw">lm</span>(dist ~<span class="st"> </span>speed, <span class="dt">data=</span>cars1), <span class="dt">col=</span><span class="st">"blue"</span>, <span class="dt">lwd=</span><span class="dv">3</span>, <span class="dt">lty=</span><span class="dv">2</span>)</code></pre></div>
<p><img src='screenshots/outliers_effect.png' width='698' height='349' /></p>
<p>Notice the change in slope of the best fit line after removing the outliers. Had we used the outliers to train the model(left chart), our predictions would be exagerated (high error) for larger values of speed because of the larger slope.</p>
<h2>Detect outliers</h2>
<h2>Univariate approach</h2>
<p>For a given continuous variable, outliers are those observations that lie outside <span class="math inline">1.5 * <em>I</em><em>Q</em><em>R</em></span>, where IQR, the ‘Inter Quartile Range’ is the difference between 75th and 25th quartiles. Look at the points outside the whiskers in below box plot.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">url <-<span class="st"> "http://rstatistics.net/wp-content/uploads/2015/09/ozone.csv"</span>
<span class="co"># alternate source: https://raw.githubusercontent.com/selva86/datasets/master/ozone.csv</span>
inputData <-<span class="st"> </span><span class="kw">read.csv</span>(url) <span class="co"># import data</span>
outlier_values <-<span class="st"> </span><span class="kw">boxplot.stats</span>(inputData$pressure_height)$out <span class="co"># outlier values.</span>
<span class="kw">boxplot</span>(inputData$pressure_height, <span class="dt">main=</span><span class="st">"Pressure Height"</span>, <span class="dt">boxwex=</span><span class="fl">0.1</span>)
<span class="kw">mtext</span>(<span class="kw">paste</span>(<span class="st">"Outliers: "</span>, <span class="kw">paste</span>(outlier_values, <span class="dt">collapse=</span><span class="st">", "</span>)), <span class="dt">cex=</span><span class="fl">0.6</span>)</code></pre></div>
<h2>Bivariate approach</h2>
<p>Visualize in box-plot of the X and Y, for categorical X’s</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">url <-<span class="st"> "http://rstatistics.net/wp-content/uploads/2015/09/ozone.csv"</span>
ozone <-<span class="st"> </span><span class="kw">read.csv</span>(url)</code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># For categorical variable</span>
<span class="kw">boxplot</span>(ozone_reading ~<span class="st"> </span>Month, <span class="dt">data=</span>ozone, <span class="dt">main=</span><span class="st">"Ozone reading across months"</span>) <span class="co"># clear pattern is noticeable.</span>
<span class="kw">boxplot</span>(ozone_reading ~<span class="st"> </span>Day_of_week, <span class="dt">data=</span>ozone, <span class="dt">main=</span><span class="st">"Ozone reading for days of week"</span>) <span class="co"># this may not be significant, as day of week variable is a subset of the month var.</span></code></pre></div>
<p><img src='screenshots/bivariate_boxplot.png' width='698' height='349' /></p>
<p>What is the inference? The change in the level of boxes suggests that <code>Month</code> seem to have an impact in <code>ozone_reading</code> while <code>Day_of_week</code> does not. Any outliers in respective categorical level show up as dots outside the whiskers of the boxplot.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># For continuous variable (convert to categorical if needed.)</span>
<span class="kw">boxplot</span>(ozone_reading ~<span class="st"> </span>pressure_height, <span class="dt">data=</span>ozone, <span class="dt">main=</span><span class="st">"Boxplot for Pressure height (continuos var) vs Ozone"</span>)
<span class="kw">boxplot</span>(ozone_reading ~<span class="st"> </span><span class="kw">cut</span>(pressure_height, <span class="kw">pretty</span>(inputData$pressure_height)), <span class="dt">data=</span>ozone, <span class="dt">main=</span><span class="st">"Boxplot for Pressure height (categorial) vs Ozone"</span>, <span class="dt">cex.axis=</span><span class="fl">0.5</span>)</code></pre></div>
<p><img src='screenshots/boxplot_continuous.png' width='698' height='349' /></p>
<p>You can see few outliers in the box plot and how the <code>ozone_reading</code> increases with <code>pressure_height</code>. Thats clear.</p>
<h2>Multivariate Model Approach</h2>
<p>Declaring an observation as an outlier based on a just one (rather unimportant) feature could lead to unrealistic inferences. When you have to decide if an individual entity (represented by row or observation) is an extreme value or not, it better to collectively consider the features (X’s) that matter. Enter Cook’s Distance.</p>
<h4>Cooks Distance</h4>
<p>Cook’s distance is a measure computed with respect to a given regression model and therefore is impacted only by the X variables included in the model. But, what does cook’s distance mean? It computes the influence exerted by each data point (row) on the predicted outcome.</p>
<p>The cook’s distance for each observation <span class="math inline"><em>i</em></span> measures the change in <span class="math inline">$\hat{Y}$</span> (fitted Y) for all observations with and without the presence of observation <span class="math inline"><em>i</em></span>, so we know how much the observation <em>i</em> impacted the fitted values. Mathematically, cook’s distance <span class="math inline"><em>D</em><sub><em>i</em></sub></span> for observation <em>i</em> is computed as:</p>
<p><br /><span class="math display">$$D{_i}=\frac{\sum_{j=1}^{n}\left( \hat{Y}_{j} - \hat{Y}_{j \left(i \right)} \right)^{2}}{p \times MSE}$$</span><br /> where,</p>
<ul>
<li><span class="math inline">$\hat{Y}_{j}$</span> is the value of <span class="math inline"><em>j</em><sub><em>t</em><em>h</em></sub></span> fitted response when all the observations are included.</li>
<li><span class="math inline">$\hat{Y}_{j \left(i \right)}$</span> is the value of <span class="math inline"><em>j</em><sub><em>t</em><em>h</em></sub></span> fitted response, where the fit does not include observation <em>i</em>.</li>
<li><span class="math inline"><em>M</em><em>S</em><em>E</em></span> is the mean squared error.</li>
<li><span class="math inline"><em>p</em></span> is the number of coefficients in the regression model.</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">mod <-<span class="st"> </span><span class="kw">lm</span>(ozone_reading ~<span class="st"> </span>., <span class="dt">data=</span>ozone)
cooksd <-<span class="st"> </span><span class="kw">cooks.distance</span>(mod)</code></pre></div>
<h5>Influence measures</h5>
<p>In general use, those observations that have a cook’s distance greater than 4 times the mean may be classified as influential. This is not a hard boundary.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">plot</span>(cooksd, <span class="dt">pch=</span><span class="st">"*"</span>, <span class="dt">cex=</span><span class="dv">2</span>, <span class="dt">main=</span><span class="st">"Influential Obs by Cooks distance"</span>) <span class="co"># plot cook's distance</span>
<span class="kw">abline</span>(<span class="dt">h =</span> <span class="dv">4</span>*<span class="kw">mean</span>(cooksd, <span class="dt">na.rm=</span>T), <span class="dt">col=</span><span class="st">"red"</span>) <span class="co"># add cutoff line</span>
<span class="kw">text</span>(<span class="dt">x=</span><span class="dv">1</span>:<span class="kw">length</span>(cooksd)+<span class="dv">1</span>, <span class="dt">y=</span>cooksd, <span class="dt">labels=</span><span class="kw">ifelse</span>(cooksd><span class="dv">4</span>*<span class="kw">mean</span>(cooksd, <span class="dt">na.rm=</span>T),<span class="kw">names</span>(cooksd),<span class="st">""</span>), <span class="dt">col=</span><span class="st">"red"</span>) <span class="co"># add labels</span></code></pre></div>
<p><img src='screenshots/cooks_distance.png' width='698' height='349' /></p>
<p>Now lets find out the influential rows from the original data. If you extract and examine each influential row 1-by-1 (from below output), you will be able to reason out why that row turned out influential. It is likely that one of the X variables included in the model had extreme values.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">influential <-<span class="st"> </span><span class="kw">as.numeric</span>(<span class="kw">names</span>(cooksd)[(cooksd ><span class="st"> </span><span class="dv">4</span>*<span class="kw">mean</span>(cooksd, <span class="dt">na.rm=</span>T))]) <span class="co"># influential row numbers</span>
<span class="kw">head</span>(ozone[influential, ]) <span class="co"># influential observations.</span>
<span class="co">#> Month Day_of_month Day_of_week ozone_reading pressure_height Wind_speed Humidity</span>
<span class="co">#> 19 1 19 1 4.07 5680 5 73</span>
<span class="co">#> 23 1 23 5 4.90 5700 5 59</span>
<span class="co">#> 58 2 27 5 22.89 5740 3 47</span>
<span class="co">#> 133 5 12 3 33.04 5880 3 80</span>
<span class="co">#> 135 5 14 5 31.15 5850 4 76</span>
<span class="co">#> 149 5 28 5 4.82 5750 3 76</span>
<span class="co">#> Temperature_Sandburg Temperature_ElMonte Inversion_base_height Pressure_gradient</span>
<span class="co">#> 19 52 56.48 393 -68</span>
<span class="co">#> 23 69 51.08 3044 18</span>
<span class="co">#> 58 53 58.82 885 -4</span>
<span class="co">#> 133 80 73.04 436 0</span>
<span class="co">#> 135 78 71.24 1181 50</span>
<span class="co">#> 149 65 51.08 3644 86</span>
<span class="co">#> Inversion_temperature Visibility</span>
<span class="co">#> 19 69.80 10</span>
<span class="co">#> 23 52.88 150</span>
<span class="co">#> 58 67.10 80</span>
<span class="co">#> 133 86.36 40</span>
<span class="co">#> 135 79.88 17</span>
<span class="co">#> 149 59.36 70</span></code></pre></div>
<p>Lets examine the first 6 rows from above output to find out why these rows could be tagged as <em>influential observations</em>.</p>
<ul>
<li>Row 58, 133, 135 have very high <code>ozone_reading</code>.</li>
<li>Rows 23, 135 and 149 have very high <code>Inversion_base_height</code>.</li>
<li>Row 19 has very low <code>Pressure_gradient</code>.</li>
</ul>
<h2>Outliers Test</h2>
<p>The function <code>outlierTest</code> from <code>car</code> package gives the most extreme observation based on the given model. Here’s an example based on the <code>mod</code> linear model object we’d just created.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">car::<span class="kw">outlierTest</span>(mod)
<span class="co">#> No Studentized residuals with Bonferonni p < 0.05</span>
<span class="co">#> Largest |rstudent|:</span>
<span class="co">#> rstudent unadjusted p-value Bonferonni p</span>
<span class="co">#> 243 3.045756 0.0026525 0.53845</span></code></pre></div>
<p>This output suggests that observation in row 243 is most extreme.</p>
<h2>outliers package</h2>
<p>The <a href="https://cran.r-project.org/web/packages/outliers/index.html">outliers package</a> provides a number of useful functions to systematically extract outliers. Some of these are convenient and come handy, especially the <code>outlier()</code> and <code>scores()</code> functions.</p>
<h5>outliers</h5>
<p><code>outliers</code> gets the extreme most observation from the mean. If you set the argument <code>opposite=TRUE</code>, it fetches from the other side.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">set.seed</span>(<span class="dv">1234</span>)
y=<span class="kw">rnorm</span>(<span class="dv">100</span>)
<span class="kw">outlier</span>(y)
<span class="co">#> [1] 2.548991</span>
<span class="kw">outlier</span>(y,<span class="dt">opposite=</span><span class="ot">TRUE</span>)
<span class="co">#> [1] -2.345698</span>
<span class="kw">dim</span>(y) <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">20</span>,<span class="dv">5</span>) <span class="co"># convert it to a matrix</span>
<span class="kw">outlier</span>(y)
<span class="co">#> [1] 2.415835 1.102298 1.647817 2.548991 2.121117</span>
<span class="kw">outlier</span>(y,<span class="dt">opposite=</span><span class="ot">TRUE</span>)
<span class="co">#> [1] -2.345698 -2.180040 -1.806031 -1.390701 -1.372302</span></code></pre></div>
<h5><code>scores</code></h5>
<p>There are two aspects to the <code>scores()</code> function.</p>
<ol style="list-style-type: decimal">
<li>Compute the normalised scores based on “z”, “t”, “chisq” etc</li>
<li>Find out observations that lie beyond a given percentile based on a given score.</li>
</ol>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">set.seed</span>(<span class="dv">1234</span>)
x =<span class="st"> </span><span class="kw">rnorm</span>(<span class="dv">10</span>)
<span class="kw">scores</span>(x) <span class="co"># z-scores => (x-mean)/sd</span>
<span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"chisq"</span>) <span class="co"># chi-sq scores => (x - mean(x))^2/var(x)</span>
<span class="co">#> [1] 0.68458034 0.44007451 2.17210689 3.88421971 0.66539631 . . .</span>
<span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"t"</span>) <span class="co"># t scores</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"chisq"</span>, <span class="dt">prob=</span><span class="fl">0.9</span>) <span class="co"># beyond 90th %ile based on chi-sq</span>
<span class="co">#> [1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE</span>
<span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"chisq"</span>, <span class="dt">prob=</span><span class="fl">0.95</span>) <span class="co"># beyond 95th %ile</span>
<span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"z"</span>, <span class="dt">prob=</span><span class="fl">0.95</span>) <span class="co"># beyond 95th %ile based on z-scores</span>
<span class="kw">scores</span>(x, <span class="dt">type=</span><span class="st">"t"</span>, <span class="dt">prob=</span><span class="fl">0.95</span>) <span class="co"># beyond 95th %ile based on t-scores</span></code></pre></div>
<h2>Treating the outliers</h2>
<p>Once the outliers are identified and you have decided to make amends as per the nature of the problem, you may consider one of the following approaches.</p>
<h4>1. Imputation</h4>
<p>Imputation with mean / median / mode. This method has been dealt with in detail in the discussion about <a href="http://r-statistics.co/Missing-Value-Treatment-With-R.html#3.%20Imputation%20with%20mean%20/%20median%20/%20mode">treating missing values</a>.</p>
<h4>2. Capping</h4>
<p>For missing values that lie outside the <span class="math inline">1.5 * <em>I</em><em>Q</em><em>R</em></span> limits, we could cap it by replacing those observations outside the lower limit with the value of 5th %ile and those that lie above the upper limit, with the value of 95th %ile. Below is a sample code that achieves this.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">x <-<span class="st"> </span>ozone$pressure_height
qnt <-<span class="st"> </span><span class="kw">quantile</span>(x, <span class="dt">probs=</span><span class="kw">c</span>(.<span class="dv">25</span>, .<span class="dv">75</span>), <span class="dt">na.rm =</span> T)
caps <-<span class="st"> </span><span class="kw">quantile</span>(x, <span class="dt">probs=</span><span class="kw">c</span>(.<span class="dv">05</span>, .<span class="dv">95</span>), <span class="dt">na.rm =</span> T)
H <-<span class="st"> </span><span class="fl">1.5</span> *<span class="st"> </span><span class="kw">IQR</span>(x, <span class="dt">na.rm =</span> T)
x[x <<span class="st"> </span>(qnt[<span class="dv">1</span>] -<span class="st"> </span>H)] <-<span class="st"> </span>caps[<span class="dv">1</span>]
x[x ><span class="st"> </span>(qnt[<span class="dv">2</span>] +<span class="st"> </span>H)] <-<span class="st"> </span>caps[<span class="dv">2</span>]</code></pre></div>
<h4>3. Prediction</h4>
<p>In yet another approach, the outliers can be replaced with missing values (NA) and then can be predicted by considering them as a response variable. We already discussed <a href="http://r-statistics.co/Missing-Value-Treatment-With-R.html#4.%20Prediction">how to predict missing values</a>.</p>
<hr />
<p>Have a suggestion or found a bug? Notify <a href="https://docs.google.com/forms/d/e/1FAIpQLSeIJmlvwe562R7JVpi5J2ydLyhk5-7OrGRMFGYrMJvjPal8eA/viewform">here.</a></p>
</div>
</div>
<div class="footer">
<hr>
<p>© 2016-17 Selva Prabhakaran. Powered by <a href="http://jekyllrb.com/">jekyll</a>,
<a href="http://yihui.name/knitr/">knitr</a>, and
<a href="http://johnmacfarlane.net/pandoc/">pandoc</a>.
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons License.</a>
</p>
</div>
</div> <!-- /container -->
<script src="//code.jquery.com/jquery.js"></script>
<script src="www/bootstrap.min.js"></script>
<script src="www/toc.js"></script>
<!-- MathJax Script -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- Google Analytics Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-69351797-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
body {
font-family: 'Helvetica Neue', Roboto, Arial, sans-serif;
font-size: 16px;
line-height: 27px;
font-weight: 400;
}
blockquote p {
line-height: 1.75;
color: #717171;
}
.well li{
line-height: 28px;
}
li.dropdown-header {
display: block;
padding: 0px;
font-size: 14px;
}
</style>
</body>
</html>