R: Find outliers with mvBACON

Viewed 530

I'm new to R and working on an assignment were I am supposed to replicate the results from a linear regression (time series data with 1360 observations and 52 variables (11 variables in the regression model)). In the original study the researchers identified outliers with the Hadi method. It seems that this is done best in R with the mvBacon function, is this correct? I cannot seem to find a good answer on how to use this though, could anyone please tell me how I can use this function to find the outliers? (I would very much appreciate an answer that is explained as simply as possible since R is very new to me). Thank you very much!

1 Answers

Yes, the mvBACON is for outlier identification based on some distance. The default one is the Mahalanobis distance. The following code will walk you through a simple example on the mtcars subdataset on how to identify outliers with mvBACON:

# load packages
library(dplyr)
library(magrittr)

# Use mtcars (sub)dataset and plot it
data <- mtcars %>% select(mpg, disp)
plot(data, main = "mtcars")

plot1

# Add some outliers and plot again
data <- rbind(data, 
              data.frame(mpg = c(1, 80), disp = c(800, 1000)))
plot(data, main = "mtcars")

plot2

# Use mvBacon to calculate the distances and get the ouliers
# install.packages("robustX) # uncomment line to install package
library(robustX)

#compute distance - default is Mahalonobis
distances <- mvBACON(data)

# Plot it again...
plot(data, main = "mtcars")

# ...with highlighting the outliers
points(data[!distances$subset, ], col = "red", pch = 19)

plot3

# Some fine tuning, since many of the outliers seem to be still good for regression
distances <- mvBACON(data, alpha = 0.6)

# update plot
plot(data, main = "mtcars")
points(data[!distances$subset, ], col = "red", pch = 19)

plot4

Related