R:聚合与timeAverage结合使用

时间:2015-02-23 11:54:51

标签: r aggregate plyr

我有一个包含每小时观察和建模的空气质量数据的数据框。其他信息是测量站,国家,站类型和型号:

> head(PM10val)
                 date station type   model country obs   mod
1 2009-01-01 00:00:00 BELAB01   sB chimere      BE  63 13.45
2 2009-01-01 01:00:00 BELAB01   sB chimere      BE  50 18.71
3 2009-01-01 02:00:00 BELAB01   sB chimere      BE  77 20.65
4 2009-01-01 03:00:00 BELAB01   sB chimere      BE  68 21.42
5 2009-01-01 04:00:00 BELAB01   sB chimere      BE  58 22.47
6 2009-01-01 05:00:00 BELAB01   sB chimere      BE  62 24.02

我想使用openair包的timeAverage函数(计算包含日期字段的数据帧的时间平均值)来计算每站和每个模型的每日或年平均值。我试过了:

> anmean <- aggregate(PM10val, by=list(PM10val$station,PM10val$model),
+         function (x) timeAverage(x,avg.time="year",data.thresh=75,    statistic="mean"))

这应该计算每个模型和站点的“obs”和“mod”的年平均值,数据捕获阈值为75%。 但它返回:

 Error in `[.default`(mydata, , Names) : incorrect number of dimensions
    11 NextMethod("[") 
10 `[.POSIXct`(mydata, , Names) 
9 mydata[, Names] 
8 checkPrep(mydata, vars, type = "default", remove.calm = FALSE, 
    strip.white = FALSE) 
7 timeAverage(x, avg.time = "year", data.thresh = 75, statistic = "mean") 
6 FUN(X[[1L]], ...) 
5 lapply(X = split(e, grp), FUN = FUN, ...) 
4 FUN(X[[1L]], ...) 
3 lapply(x, function(e) {
    ans <- lapply(X = split(e, grp), FUN = FUN, ...)
    if (simplify && length(len <- unique(sapply(ans, length))) == 
    1L) { ... 
2 aggregate.data.frame(PM10val, by = list(PM10val$station, PM10val$model), 
    function(x) timeAverage(x, avg.time = "year", data.thresh = 75, 
        statistic = "mean")) 
1 aggregate(PM10val, by = list(PM10val$station, PM10val$model), 
    function(x) timeAverage(x, avg.time = "year", data.thresh = 75, 
        statistic = "mean"))  

我做错了什么?我总是可以使用循环,但我不认为这是要走的路。 谢谢!

1 个答案:

答案 0 :(得分:1)

我建议改用ddplyPOSIXct数据类型和aggregate存在一些问题。实际上,您的函数将x视为日期,而不是子data.frame。

以下代码适用于比利时数据。 函数ddply执行相同操作,它按您指定的级别拆分为第二个参数c("site", "country"),首先将按&#34; site&#34;拆分。然后由&#34; country&#34;,然后为每个分组应用函数。我已将函数包装到Funfun只是为了缩短代码。此外,只需为importAirbase函数中的绑定数据设置bind_rows = rbind.fill的技术性。您可以将data2替换为您的数据,它应该有效。

library(plyr)
Funfun = function (x) timeAverage(x, avg.time="year", data.thresh=75, statistic="mean")
bind_rows = rbind.fill
data2 = importAirbase(site = c("BELAB01","BELAB02") , year = 2011:2012, pollutant = NA,
    add = c("country", "site.type"), splice = FALSE, local = NA)
ddply(data2, c("site", "country"), Funfun)