如何从数据集列表中删除异常值

问题描述 投票:0回答:1

我正在尝试从两个数据集的列表中删除异常值:

#creation of dataset
repr = list(mtcars, airquality)

#detectig boxplot
g_stats = lapply(repr, function(x) boxplot(x, main = "Boxplot")$out)

这是我用 lapply 应用的代码:

new = lapply(repr, function(x) 
  x[ !(x %in% g_stats), ])

不幸的是,我可以看到在新的数据集列表中,根本没有区别(至少行号应该有所不同,但我不会有条件地将 lapply 函数用于具有异常值的列表)。

任何人都可以提出建议吗? 谢谢

r dataset lapply outliers
1个回答
0
投票

我们可以使用

Map
:它类似于
lapply
,但它不是只接受一个列表,而是接受任意数量的列表。

repr = list(mtcars, airquality)
g_stats = lapply(repr, function(x) boxplot(x, main = "Boxplot", plot = FALSE)$out)
sapply(repr, nrow)
# [1]  32 153
repr2 <- Map(function(x, out) x[rowSums(apply(x, 1, `%in%`, out)) == 0,], repr, g_stats)
sapply(repr2, nrow)
# [1] 18 75

数据确实不一样:

lapply(repr, head)
# [[1]]
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
# [[2]]
#   Ozone Solar.R Wind Temp Month Day
# 1    41     190  7.4   67     5   1
# 2    36     118  8.0   72     5   2
# 3    12     149 12.6   74     5   3
# 4    18     313 11.5   62     5   4
# 5    NA      NA 14.3   56     5   5
# 6    28      NA 14.9   66     5   6
lapply(repr2, head)
# [[1]]
#                    mpg cyl  disp  hp drat   wt  qsec vs am gear carb
# Mazda RX4         21.0   6 160.0 110 3.90 2.62 16.46  0  1    4    4
# Datsun 710        22.8   4 108.0  93 3.85 2.32 18.61  1  1    4    1
# Hornet Sportabout 18.7   8 360.0 175 3.15 3.44 17.02  0  0    3    2
# Merc 240D         24.4   4 146.7  62 3.69 3.19 20.00  1  0    4    2
# Merc 230          22.8   4 140.8  95 3.92 3.15 22.90  1  0    4    2
# Merc 280          19.2   6 167.6 123 3.92 3.44 18.30  1  0    4    4
# [[2]]
#    Ozone Solar.R Wind Temp Month Day
# 4     18     313 11.5   62     5   4
# 5     NA      NA 14.3   56     5   5
# 6     28      NA 14.9   66     5   6
# 10    NA     194  8.6   69     5  10
# 11     7      NA  6.9   74     5  11
# 12    16     256  9.7   69     5  12
© www.soinside.com 2019 - 2024. All rights reserved.