r - 如何查找数据框中两列的异常值
问题描述
我需要为每种类型的变量 2 和变量 3 获取变量 1 的异常值总数,然后将其显示在表格中。它还需要仅显示 variable4 大于 1.5 的情况。我让它工作了,但我认为我的代码有问题,因为每个的输出都是 0,这是不正确的。
当我做 boxplot.stats(df$variable1)$out 时,我会得到大量异常值。但是当我使用下面的代码时,每个代码都显示为 0。
high <- mean(df$variable1) + sd(df$variable1) * 3
low <- mean(df$variable1) - sd(df$variable1) * 3
df%>%
filter(varaible4>1.5)%>%
group_by(variable2, variable3) %>%
tally(variable1 < low ||variable1 > high)
每种类型的变量 2 和变量 3 都会显示一个表格……但每个变量的计数都显示为 0。
解决方案
数据:
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
}
}
)
)
推荐阅读
- javascript - 使用 JSON 数据在 javascript 中创建 Google 图表
- c# - 从 Windows 复制文本时如何粘贴到文本框 (C#)
- azure - 从 AKS 主节点读取
- reactjs - react中setState是浅拷贝还是深拷贝
- regex - 从单行中提取多个值并将它们放在正则表达式中的同一组中
- python - 如何将一列中的每个单元格与熊猫中的特定值进行比较?
- wordpress - 在 WooCommerce 的购物车页面上更新数量时拆分购物车项目
- ios - 在调用错误时,就像使用未声明的类型“区”一样
- ios - AVPlayerItem.duration 和 AVPlayerItem.asset.duration 有什么区别?
- r - read.xlsx 文件,其中一列包含“数字作为文本”