数据:
df <- data.frame(variable1 = runif(1000,1,10),
variable2 = round(runif(1000,1,3)),
variable3 = round(runif(1000,1,3)),
variable4 = runif(1000,1,5),
variable5 = rep(LETTERS[1:4], 250),
variable6 = rep(LETTERS[5:9], 200), stringsAsFactors = F)
df$variable1[c(5,13,95)] = 1000
多元异常值检测:
# Create a grouping vector:
grouping_vars <- c("variable5", "variable6")
# Split apply combine function:
tmp_df <- do.call(rbind, lapply(split(df[,sapply(df, is.numeric)], df[,grouping_vars]), function(x){
# Calculate mahalanobis distance:
md <- mahalanobis(x, colMeans(x), cov(x), inverted = FALSE)
# Calculate the iqr of the md:
iqr <- quantile(md, .75) - quantile(md, .25)
# Classify the lower threshold outliers:
lwr <- ifelse(md > (quantile(md, .75) + (1.5 * iqr)) | (md < (quantile(md, .25) - (1.5 * iqr))),
"outlier",
"not outlier")
# Classify the upper threshold outliers:
upr <- ifelse(md > (quantile(md, .75) + (3 * iqr)) | (md < (quantile(md, .25) - (3 * iqr))),
"outlier",
"not outlier")
# Bind all of the vecs together:
cbind(x, md, lwr, upr)
}
)
)
# Extract the group from the row names:
tmp_df <- data.frame(cbind(df[,!(sapply(df, is.numeric))],
grouping_vars = row.names(tmp_df), tmp_df), row.names = NULL)
df <- tmp_df[,c(names(df), setdiff(names(tmp_df), names(df)))]
单变量异常值检测:
# Use boxplot stats mean(x) +- 1.5 * IQR:
outliers_classified <- do.call("rbind", lapply(split(df, df[,grouping_vars]), function(x){
if(is.numeric(x)){
ifelse(x %in% boxplot.stats(x)$out, NA, x)
}else{
x
}
}
)
)