library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(outliers)

1. Z-score

Quy luật 3sigma

mtcars[1, 1] <- 50
mtcars
UB <- mean(mtcars$mpg) + 3*sd(mtcars$mpg)
LB <- mean(mtcars$mpg) - 3*sd(mtcars$mpg)
filter(mtcars, mpg > UB | mpg < LB)


Trung bình bị ảnh hưởng bởi giá trị đột xuất

mtcars[1, 1] <- 50
mean(mtcars$mpg)
## [1] 20.99687
median(mtcars$mpg)
## [1] 19.2

2. Hampel Filter

Tốt hơn z-score vì không sử dụng số trung bình, thay bằng số trung vị

mtcars[1, 1] <- 50
UB <- median(mtcars$mpg) + 3*mad(mtcars$mpg)
LB <- median(mtcars$mpg) - 3*mad(mtcars$mpg)
filter(mtcars, mpg > UB | mpg < LB)

3. boxplot

Là outliers nếu:

mtcars[2, 1] <- 45
boxplot(mtcars$mpg, horizontal = TRUE)

mybox <- boxplot(mtcars$mpg)

mybox
## $stats
##       [,1]
## [1,] 10.40
## [2,] 15.35
## [3,] 19.20
## [4,] 25.20
## [5,] 33.90
## 
## $n
## [1] 32
## 
## $conf
##          [,1]
## [1,] 16.44882
## [2,] 21.95118
## 
## $out
## [1] 50 45
## 
## $group
## [1] 1 1
## 
## $names
## [1] "1"
mybox$out
## [1] 50 45
filter(mtcars, mpg %in% mybox$out)
# lọc bỏ quan sát bị đột xuất
filter(mtcars, !(mpg %in% mybox$out))

4. Histogram

hist(mtcars$mpg, breaks = 20)

5. Kiểm định

grubbs.test(mtcars$mpg, two.sided = T)
## 
##  Grubbs test for one outlier
## 
## data:  mtcars$mpg
## G = 3.11412, U = 0.67708, p-value = 0.02213
## alternative hypothesis: highest value 50 is an outlier
# chỉ dành cho data có cơ mẫu nhỏ (3 - 30)
# dixon.test(mtcars$mpg)

6. Đột xuất đa biến

plot(mtcars$mpg, mtcars$hp)

m1 <- lm(hp ~ mpg, data=mtcars)
cooks.distance(m1)[1] 
## Mazda RX4 
##   1.19661
#lấy ra khoảng cách cook đầu tiên


cookd <- cooks.distance(m1)

Lọc ra quan sát có khoảng cách Cook > 4*mean(kcach Cook)

mtcars[cookd > 4*mean(cookd), ]