假设我拥有过去20年的最高温度数据。我的数据框有一个月,日,年和MAX_C(温度数据)列。我想计算从一年的6月31日到前一年的7月1日的平均(和标准偏差和范围)最高温度(即从1991年7月1日到1992年6月31日的平均最高日温度)。有没有一种有效的方法呢?
到目前为止,我的方法是创建一个数组:
maxt.prev12<-tapply(maxt$MAX_C,INDEX=list(maxt$month,maxt$day,maxt$year),mean)
我把平均值放在函数中,因为tapply在INDEX之后没有生成没有函数的数组,但是函数实际上并不是在这里计算任何东西。然后我考虑尝试将1月到6月从一个矩阵(即1992年)和7月到12月从前一个矩阵(即1991年)开始,然后计算均值。我不完全确定如何做到这一点,但是,必须有一种更有效的方法在R中执行这些计算
修改 这是一个简单的数据样本集
maxt
day month year MAX_C
1 1 1990 29
1 2 1990 28
1 3 1990 32
1 4 1990 26
1 5 1990 24
1 6 1990 32
1 7 1990 30
1 8 1990 28
1 9 1990 28
1 10 1990 24
1 11 1990 30
1 12 1990 30
1 1 1991 25
1 2 1991 26
1 3 1991 28
1 4 1991 25
1 5 1991 24
1 6 1991 32
1 7 1991 26
1 8 1991 32
1 9 1991 26
1 10 1991 26
1 11 1991 27
1 12 1991 26
1 1 1992 27
1 2 1992 25
1 3 1992 29
1 4 1992 32
1 5 1992 27
1 6 1992 27
1 7 1992 24
1 8 1992 25
1 9 1992 28
1 10 1992 26
1 11 1992 31
1 12 1992 27
答案 0 :(得分:1)
我会创建一个“指标年”列,该列等于7月至12月的月份,但等于1月至6月的月份1。
根据数字而不是字符来编辑月份参考:
> maxt$year2 <- maxt$year
> maxt[ maxt$month %in% 1:6, "year2"] <-
+ maxt[ maxt$month %in% 1:6, "year"] -1
> # month.name is a 12 element constant vector in all versions of R
> # check that it matches the spellings of your months
>
> mean_by_year <- tapply(maxt$MAX_C, maxt$year2, mean, na.rm=TRUE)
> mean_by_year
1989 1990 1991 1992
28.50000 27.50000 27.50000 26.83333
如果您想更改标签,以便它们反映非日历年推导:
> names(mean_by_year) <- paste(substr(names(mean_by_year),3,4),
+ as.character( as.numeric(substr(names(mean_by_year),3,4))+1),
sep="_")
> mean_by_year
89_90 90_91 91_92 92_93
28.50000 27.50000 27.50000 26.83333
虽然我不认为在千禧年的转折时会是正确的。