更新时间:2022-03-22 23:45:52
好,我有一些东西.也许您可以用它来修改您的功能:
Ok, I've got a little something. Maybe you an use it to modify your function:
## Generate your layer names (used for indexing later)
nms <- expand.grid(paste0('X',1969:2011),c("01","02","03","04","05","06","07","08","09","10","11","12"),'16')
nms <- apply(nms,1,function(x) paste0(x,collapse = '.'))
nms <- sort(nms)
## Generating fake raster brick
r <- raster()
r[] <- runif(ncell(r))
rst <- lapply(1:length(nms),function(x) r)
rst <- do.call(brick,rst)
names(rst) <- nms
现在,您可以使用层名称对砖进行索引了.循环浏览飓风季节(从Year -1开始):
And now you can index the brick with the layer names. Loop through the Hurricane Seasons (starting with Year1 -1):
for (ix in 1970:2011){
sel <- rst[[c(grep(paste0(ix-1,'.12'),nms),sapply(paste0(0,1:4),function(x) grep(paste0(ix,'.',x),nms)))]]
break ## in case you don't want to go through all iterations
}
对于第一次迭代,我得到以下输出:
For the first iteration, I'm getting this output:
> sel
class : RasterStack
dimensions : 180, 360, 64800, 5 (nrow, ncol, ncell, nlayers)
resolution : 1, 1 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
names : X1969.12.16, X1970.01.16, X1970.02.16, X1970.03.16, X1970.04.16
min values : 5.988637e-06, 5.988637e-06, 5.988637e-06, 5.988637e-06, 5.988637e-06
max values : 0.9999771, 0.9999771, 0.9999771, 0.9999771, 0.9999771
让我知道是否有帮助.
所以也许是一个更适用的示例:
So maybe a more applicable example:
(该函数假定您输入砖的层名称x
的格式为Xyyyy.mm.dd
)
(the function assumes your layer names of your input brick x
have the format Xyyyy.mm.dd
)
hadSSTmean <- function(x, years, first.range = 11:12, second.range = 1:4){
nms <- names(x)
mts <- c("01","02","03","04","05","06","07","08","09","10","11","12")
xMeans <- vector(length = length(years)-1,mode='list')
for (ix in 2:length(years){
xMeans[[ix-1]] <- mean(x[[c(sapply(first.range,function(x) grep(paste0(years[ix-1],'.',mts[x]),nms)),sapply(1:4,function(x) grep(paste0(years[ix],'.',mts[x]),nms)))]])
}
return(do.call(brick,xMeans))
# you could also return the list instead of a single brick
}