在 data.table 中使用分位数函数
Using quantile function in data.table
我尝试计算 data.table 中某些值的平均值。平均值应该在没有异常值的情况下计算,这意味着我必须先过滤数据。
为了在我的数据中定义异常值,我使用 "default boxplot" 方法。
这种方法非常有效:
test <- template[Month==1] # create small subset with data from January
qnt <- quantile(test$x,c(.25,.75)
H <- 1.5 * IQR(test$x)
test[x < (qnt[2]+H) & x > (qnt[1]-H),mean(add)]
[1] -6113.136
我也可以在数据表中进行计算:
test <- template[Month==1] # create small subset with data from January
test[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)]
[1] -6113.136
因为我不仅需要 1 月的平均值,而且需要所有月份的平均值,所以我尝试了这个:
template[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x),by=Month]
1: 1 -5601.3050 <<< not the same value than before
2: 2 1187.3186
...
上次进场的一月与之前的一月不同。据我所知, quantile() 方法是问题所在。我想它不包括 data.table.
的 'by=Month' 分组
我的一般做法有什么问题吗?
有没有一种方法可以在不首先将 'template' data.table 拆分为 12 个较小的表的情况下进行这些计算?
非常感谢您的帮助!
更新:
template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
1: 1 -6113.1362
2: 2 1529.4808
感谢@Frank 和@Roland 的超快支持!
template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
正如 Frank 和 Roland 所说,我需要更改我的表达方式,因为 DT[i,j,by]
中的 i
arg 不使用 by 分组。使用 .SD[]
是解决方案
我尝试计算 data.table 中某些值的平均值。平均值应该在没有异常值的情况下计算,这意味着我必须先过滤数据。 为了在我的数据中定义异常值,我使用 "default boxplot" 方法。
这种方法非常有效:
test <- template[Month==1] # create small subset with data from January
qnt <- quantile(test$x,c(.25,.75)
H <- 1.5 * IQR(test$x)
test[x < (qnt[2]+H) & x > (qnt[1]-H),mean(add)]
[1] -6113.136
我也可以在数据表中进行计算:
test <- template[Month==1] # create small subset with data from January
test[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)]
[1] -6113.136
因为我不仅需要 1 月的平均值,而且需要所有月份的平均值,所以我尝试了这个:
template[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x),by=Month]
1: 1 -5601.3050 <<< not the same value than before
2: 2 1187.3186
...
上次进场的一月与之前的一月不同。据我所知, quantile() 方法是问题所在。我想它不包括 data.table.
的 'by=Month' 分组我的一般做法有什么问题吗? 有没有一种方法可以在不首先将 'template' data.table 拆分为 12 个较小的表的情况下进行这些计算?
非常感谢您的帮助!
更新:
template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
1: 1 -6113.1362
2: 2 1529.4808
感谢@Frank 和@Roland 的超快支持!
template[,.SD[x < (quantile(x,0.75)+1.5*IQR(x)) & x > (quantile(x,0.25)-1.5*IQR(x)),mean(x)],by=Month]
正如 Frank 和 Roland 所说,我需要更改我的表达方式,因为 DT[i,j,by]
中的 i
arg 不使用 by 分组。使用 .SD[]
是解决方案