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)
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
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)
Là outliers nếu:
Giá trị > q3 + 1.5IQR
Giá trị < q1 - 1.5 IQR
IQR: khoảng cách từ q3 tới q1 = q3 - q1
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))
hist(mtcars$mpg, breaks = 20)
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)
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), ]