raster :: stackApply仅返回NA值

时间:2019-08-05 08:24:28

标签: r raster netcdf

我有一个RasterBrick,其中包含平均值,即72年间隔中每个月的一层。我想获取每年的平均值-即返回72层RasterBrick

以下代码已在其他类似的栅格上工作,产生了预期的结果(发现here):

data <- raster::brick(".../air.mon.mean.nc", varname = "air")

index <- format(as.Date(raster::getZ(data), format = "%Y-%m-%d %H:%M:%S"), format = "%Y")
index <- as.numeric(index)

yearly <- raster::stackApply(data, index, fun = mean) 

> yearly
class      : RasterBrick 
dimensions : 360, 720, 259200, 72  (nrow, ncol, ncell, nlayers)
resolution : 0.5, 0.5  (x, y)
extent     : 0, 360, -90, 90  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
source     : C:/Users/villar/AppData/Local/Temp/RtmpAbUQQT/raster/r_tmp_2019-08-05_102157_18368_64365.grd 
names      : index_1948, index_1949, index_1950, index_1951, index_1952, index_1953, index_1954, index_1955, index_1956, index_1957, index_1958, index_1959, index_1960, index_1961, index_1962, ... 
min values :         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA, ... 
max values :         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA,         NA, ... 

但是,当运行此数据时,它仅返回NA值。

fun = function(x, na.rm) {sum(x)/12}不起作用,添加na.rm = TRUE也不起作用。

任何帮助将不胜感激!

数据是从here(air.mon.mean.nc)下载的。

2 个答案:

答案 0 :(得分:0)

我不知道为什么raster会这样。我可以复制它。但是,如果可以使用CDO,则可以使用运算符yearmean来获取所需的输出:cdo yearmean input.grb output.grb。这也将比使用单个内核的任何R实现都要快。

如果您希望留在R中,建议您看看新的但很棒的stars软件包。

您可以执行以下操作:

library(stars)

s = read_stars(s)

yrs = st_get_dimension_values(s, 'time') %>% format('%Y') %>% as.numeric
mymean = function(v, indices, fun = mean, na.rm = FALSE) {
    sapply(unique(indices), function(i) fun(v[indices == i], na.rm = na.rm))
}

yearly = st_apply(s, 1:2, mymean, indices = yrs, na.rm = TRUE)

您也可以选择使用此多核(请参阅?st_apply),但我怀疑无论如何它都会比准系统CDO更快。

答案 1 :(得分:0)

我遇到了同样的问题,但这对我calc(data,fun=function(x) { by(x, index, sum)})有效。您可以使用stackApply函数解决该问题吗?