计算均值并从数据中除以r中的小时数得出的离群值

时间:2018-09-13 17:15:21

标签: r aggregate average outliers

part of data我正在尝试从大型数据集(4个月的数据)中计算每小时测量值的平均值(约每小时20次),但我需要每小时删除定义为距离小时均值2SD。

structure(list(YEAR = c(2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L), MONTH = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), DAY = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L), HOUR = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), MINUTE = c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), SECOND = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L), Tmp = c(25.6984, 25.6967, 25.6962, 25.6962, 
25.6955, 25.6949, 25.6959, 25.6944, 25.6954, 25.6954, 25.6958, 
25.6958, 25.6962, 25.6967, 25.6982, 25.6976, 25.6978, 25.6977, 
25.6975, 25.6979, 25.5552, 25.5577, 25.5579, 25.5573, 25.746, 
25.7248, 25.7164, 25.7249, 25.7379, 25.752, 25.7502, 25.7678, 
25.7805, 25.7871, 25.7863, 25.7856, 25.7948, 25.7939, 25.7953, 
25.7969, 25.7982, 25.7981, 25.7972, 25.7978, 25.644, 25.6451, 
25.6455, 25.6456, 25.6451, 25.6454)), row.names = c(NA, 50L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

考虑基础R的ave(来自内置stats库以进行内联聚合)以计算离群值

df$outlier <- ave(df$Tmp, df$HOUR, 
                  FUN=function(x) (x < (mean(x) - sd(x)*2)) | (x > (mean(x) + sd(x)*2)))

然后是相应的子集:

subdf <- subset(df, outlier == 0)