计算时间序列部分的平均值

时间:2016-11-29 10:22:55

标签: r time-series mean

我有一个年度值的数据框,看起来像这样:

Time             Value
01/2000-12/2000   123
01/2001-12/2001   126
01/2002-12/2002   129
...
01/2040-12/2040   223

我想计算时间序列某些部分的平均值(例如2010-2015; 2015-2020等)

谁能告诉我怎么做?

2 个答案:

答案 0 :(得分:1)

# first extract the year
df$year <- as.numeric(sub(".*\\/", "", df$Time))
# then a simple mean() does the work for you!
mean(df$Value[df$year >= 2000 & df$year <= 2005])

答案 1 :(得分:0)

如果您的专栏Time采用Date格式,您可以这样做:

要将列转换为日期格式,请使用:

my.data.frame$Date = as.Date(paste("01.01.",sub(".*\\/", "", my.data.frame$Time),sep = ""),format = "%d.%m.%Y")

然后计算平均值:

mean(my.data.frame[my.data.frame$Date >= "2016-01-01" & my.data.frame$Date <= "2020-01-01","Value"])