计算每年特定时间段的平均值 [英] Calculating average for certain time period in every year

查看:95
本文介绍了计算每年特定时间段的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每年为我的数据计算季节平均值,平均值的计算不在同一日历年中.我已经按日期定义了季节,并希望计算每年该时间段的平均温度,降水量等(例如 12/21/1981 02/15/1982 12/21/1982 02/15/1983 )等等.

I need to calculate seasonal averages for my data every year, the calculation of average is not in the same calendar year. I have defined season by date and am looking to calculate average temperature, precipitation etc for that time period every year (eg 12/21/1981 to 02/15/1982 , 12/21/1982 to 02/15/1983) and so on.

在R中是否有一种有效的方法?

Is there an efficient way of doing this in R?

以下是我的数据:

library(xts)
seq <- timeBasedSeq('1981-01-01/1985-06-30') 
Data <- xts(1:length(seq),seq) 

谢谢

推荐答案

如果我们将时间提前11天,那么我们想要的日期就是2月26日或之前的日期,因此让 tt 这样日期向量,而 ok 是逻辑向量,如果相应的 tt 元素在2月26日当天或之前,则为TRUE.最后,在期间年末汇总 Data [ok] .

If we push the time forward by 11 days then the dates we want are those at or before February 26th so let tt be such a date vector and ok be a logical vector which is TRUE if the corresponding tt element is at or before Febrary 26th. Finally aggregate Data[ok] by end of period year.

tt <- time(Data) + 11
ok <- format(tt, "%m-%d") < "02-26"
aggregate(Data[ok], as.integer(as.yearmon(tt))[ok], mean)

给予:

1981   23.0
1982  382.5
1983  747.5
1984 1112.5
1985 1478.5

如果您想在不使用xts的情况下进行操作,则假定我们的输入是 DF ,请尝试以下操作:

If you want to do it without xts then assume our input is DF try this:

DF <- fortify.zoo(Data) # input

tt <- DF[, 1] + 11
ok <- format(tt, "%m-%d") < "02-26"
year <- as.numeric(format(tt, "%Y"))
aggregate(DF[ok, -1, drop = FALSE], list(year = year[ok]), mean)

这篇关于计算每年特定时间段的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆