离群值:如何在R中的数据集中标记离群值?

时间:2019-01-31 02:25:34

标签: r loops dplyr

我正在尝试从数据集中提取离群值并相应地对其进行标记。

样本数据

     Doctor Name    Hospital Assigned         Region    Claims   Illness Claimed
1    Albert         Some hospital Center      R-1       20       Sepsis
2    Simon          Another hospital Center   R-2       21       Pneumonia
3    Alvin          ...                       ...       ...       ...
4    Robert
5    Benedict
6    Cruz

因此,我试图将Doctor中的每个Claimed中的某个Illness分组到某个Region中,并尝试在其中找到异常值。

Doctor Name    Hospital Assigned         Region    Claims   Illness Claimed is_outlier
1    Albert    Some hospital Center      R-1       20       Sepsis         1
2    Simon     Another hospital Center   R-2       21       Pneumonia      0
3    Alvin       ...                       ...       ...       ...
4    Robert
5    Benedict
6    Cruz

我可以在Power BI中执行此操作。但是我似乎无法在R中做到这一点。我猜想其中涉及group_by()的{​​{1}}函数。但是我不确定。

这是我要实现的目标:

sample

算法如下:

dplyr

我之前已经做过,但是这段代码遍历每个疾病,并对每个疾病应用线性回归。这与我想要达到的目标接近吗?

Read data
Group data by Illness
    Group by Region
    get IQR based on Claims Count
    if claims count > than (Q3 + 1.5) * IQR
        then tag it as outlier = 1
    else
        not an outlier = 0
Export data

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用 group_by + boxplot_stats 。第一个将完成组的所有组合,第二个将返回离群值:

df.assign(city=[' '.join(s.split(', ', 1)[::-1]) for s in df['city']])

                city
0    City of Bristol
1  City of Newcastle
2             London

我希望它能起作用。

相关问题