在数据框df中提供如下所示的数据,需要提取其中任何列都有异常值的行。
text = "
A,B,C,D,E,F,G
93,53,221,314,104,721,179
100,58,218,318,93,718,181
601,61,228,829,106,739,190
510,60,229,739,95,707,181
779,51,242,1021,105,756,180
848,57,228,1076,93,710,191
94,52,227,321,95,723,179
712,58,242,954,486,750,180
,53,,10289,298,841,210
696,53,233,929,95,751,180
101,57,220,321,415,796,179
100,60,226,326,104,744,180
181,58,234,415,105,2870,468
,57,,10277,,,918
"
df = read.table(textConnection(text), sep=",", header = T)
离群值定义为箱图-Q1-1.5IQR / Q3 + 1.5IQR。因此,具有任意列(一个或多个)的列具有离群值的行将出现在我们的输出集中。
还希望获得第二组行,其中任何列值仅高于Q3 + 1.5IQR值的行都将位于我们的输出集中,而不是上述的经典定义。
完成这项工作面临着一些挑战。我在想的伪代码如下
关于#1,我尝试了以下方法
> sapply(df, boxplot.stats)
A B C D E F G
stats Numeric,5 Numeric,5 Numeric,5 Numeric,5 Numeric,5 Numeric,5 Numeric,5
n 12 14 12 14 13 13 14
conf Numeric,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2 Numeric,2
out Integer,0 Integer,0 Integer,0 Integer,2 Integer,3 Integer,2 Integer,3
但是,这似乎并没有提供可能在#2中使用过的类似stats
a vector of length 5, containing the extreme of the lower whisker, the lower ‘hinge’, the median, the upper ‘hinge’ and the extreme of the upper whisker.
的输出。
答案 0 :(得分:1)
我们可以编写一个函数来确定该值是否是异常值
IsOutlier <- function(data) {
lowerq = quantile(data, na.rm = TRUE)[2]
upperq = quantile(data, na.rm = TRUE)[4]
iqr = upperq - lowerq
threshold_upper = (iqr * 1.5) + upperq
threshold_lower = lowerq - (iqr * 1.5)
data > threshold_upper | data < threshold_lower
}
并选择至少包含一个异常值的行
df[rowSums(sapply(df, IsOutlier), na.rm = TRUE) > 0, ]
# A B C D E F G
#8 712 58 242 954 486 750 180
#9 NA 53 NA 10289 298 841 210
#11 101 57 220 321 415 796 179
#13 181 58 234 415 105 2870 468
#14 NA 57 NA 10277 NA NA 918
类似地,对于第二组,我们可以使用此功能
IsOutlier_upper <- function(data) {
upperq = quantile(data, na.rm = TRUE)[4]
lowerq = quantile(data, na.rm = TRUE)[2]
iqr = upperq - lowerq
data > (upperq + 1.5 * iqr)
}