使用 r 中的栅格包聚合季节性均值 [英] Aggregating seasonal means with the raster package in r

查看:78
本文介绍了使用 r 中的栅格包聚合季节性均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将每日数据(35 年)汇总到每月,然后使用 R 中的栅格包计算季节性平均值(我知道如何使用 CDO 进行计算).下面是我的代码,它输出所有年份的 4 个季节性平均值(140 层).如何循环输出仅 4 层(4 个季节)?.我感谢您的帮助.

I am attempting to aggregate daily data (35 years) to monthly then calculate seasonal mean using the raster package in R (I know how to do it with CDO). Below is my code, which outputs 4 seasonal means for all years (140 layers). How can I loop to output only 4 layers ( for the 4 seasons)?. I appreciate your help.

dailydata <- brick ("dailyrain.nc")  
dates <- seq(as.Date("1981-01-01"), as.Date("2015-12-31"), by="day")  
months <- format(dates, "%Y-%m")

Aggregate2Monthly <- function(x) {  
  agg <- aggregate(x, by=list(months), sum)  
  return(agg$x)  
}  
mothlydata <- calc(dailydata, Aggregate2Monthly) 

mondates <- seq(as.Date("1981-01-01"), as.Date("2015-12-31"), by="month")  
years <- format(mondates, "%Y")  
seasons.def=c(1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4)  
years.seasons <- paste(years, seasons.def, sep="-") 

nyears <- years[!duplicated(years)]  
nseas <- seasons.def[!duplicated(seasons.def)] 

Aggregate2Seasons <- function(x) {  
  agg <- aggregate(x, by=list(years.seasons), mean)  
  return(agg$x)  
}  
seasonsdata <- calc(mothlydata, Aggregate2Seasons)  

推荐答案

您希望按年和月的组合进行聚合.

You want to aggregate by a combination of year and month.

months <- format(dates, "%Y-%m")

分组月份(根据您的评论):

Grouping months (as per your comment):

groups <- function(x) {
    d <- as.POSIXlt(x)

    ans <- character(length(x))
    ans[d$mon %in%  0:1] <- "JF"
    ans[d$mon %in%  2:4] <- "MAM"
    ans[d$mon %in%  5:8] <- "JJAS"
    ans[d$mon %in% 9:11] <- "OND"
    ans
}

现在使用 groups(dates) 作为分组变量.检查:

Now use groups(dates) as the grouping variable. Check:

data.frame(dates, groups(dates))
##            dates groups.dates.
## 1     1981-01-01            JF
## 2     1981-01-02            JF
## 3     1981-01-03            JF
## 4     1981-01-04            JF
## 5     1981-01-05            JF
## 6     1981-01-06            JF

这篇关于使用 r 中的栅格包聚合季节性均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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