0

我在使用 RasterStack 循环时遇到了一点问题。我正在尝试提取过去 10 年中北卡罗来纳州每个县每小时的平均温度。我能够运行一些简单的代码并相对轻松地为每一层获取此代码,但是当我尝试循环此过程以获取光栅堆栈/砖中每个时间戳的平均值时,我运气不佳!我将不胜感激任何帮助或建议。

library(tidyverse)
library(rgdal)
library(sp)
library(raster)
library(doParallel)
library(foreach)
library(ncdf4)
librarcy(exactextractr)

# Brick the NC File 
r<-stack("ERA_Temps.nc") 

output <- for (i in 1:length(r)) {
                    
              wgsraster <- r[[i]]
                    
              year <- str_sub(names(wgsraster), 2, 5)
              month <- str_sub(names(wgsraster), 7, 8)
              day <- str_sub(names(wgsraster), 10, 11)
              hour <- str_sub(names(wgsraster), 13, 14)
                    
              NC_Counties <- cbind(shp, exact_extract(wgsraster, shp, c('mean')))
                    
              output_df <- data.frame(County.Name = NC_Counties$NAME, GEOID = NC_Counties$GEOID, temp_mean = NC_Counties$mean, year, month, day, hour)
                    return(output_df)
                  }

Output <- output_df

示例和更多信息:

 r
    class      : RasterStack 
    dimensions : 81, 81, 6561, 72  (nrow, ncol, ncell, nlayers)
    resolution : 0.25, 0.25  (x, y)
    extent     : -90.125, -69.875, 24.875, 45.125  (xmin, xmax, ymin, ymax)
    crs        : +proj=longlat +datum=WGS84 +no_defs 
    names      : X2018.09.14.00.00.00, X2018.09.14.01.00.00, X2018.09.14.02.00.00, X2018.09.14.03.00.00, X2018.09.14.04.00.00, X2018.09.14.05.00.00, X2018.09.14.06.00.00, X2018.09.14.07.00.00, X2018.09.14.08.00.00, X2018.09.14.09.00.00, X2018.09.14.10.00.00, X2018.09.14.11.00.00, X2018.09.14.12.00.00, X2018.09.14.13.00.00, X2018.09.14.14.00.00, ... 

我可以很容易地获得单个图层所需的内容:

wgsraster <- r[[5]]
                
year <- str_sub(names(wgsraster), 2, 5)
month <- str_sub(names(wgsraster), 7, 8)
day <- str_sub(names(wgsraster), 10, 11)
hour <- str_sub(names(wgsraster), 13, 14)
                
NC_Counties <- cbind(shp, exact_extract(wgsraster, shp, c('mean')))
                
output_df <- data.frame(County.Name = NC_Counties$NAME, GEOID = NC_Counties$GEOID, temp_mean = NC_Counties$exact_extract.wgsraster..shp..c..mean...,
                                        year, month, day, hour)

output_df
     County.Name GEOID temp_mean year month day hour
1         Saluda 45081  298.3141 2018    09  14   11
2   Williamsburg 45089  300.2301 2018    09  14   11
3     Dorchester 45035  299.3716 2018    09  14   11
4       Berkeley 45015  299.7389 2018    09  14   11
5      Greenwood 45047  298.5175 2018    09  14   11

但是当我尝试运行上面提到的循环时,它要么失败并且没有输出,要么给出以下错误:

Error in .local(x, i, j, ...) : you must provide an index
4

0 回答 0