Extracting data from raster file to match with shp file

家住魔仙堡 提交于 2020-12-15 05:41:28

问题


UPDATE: UPDATE: The problem was that my way to produce the grid cells has led to a wrong projection of my shapefile which resulted in the above mentioned error. I was able to produce another form of grid cells that worked perfectly with my projection.

After I successfully created a raster grid for the world map (How to generate 10x10km grid cells of all countries?)

library(sf)
library(stars)
library(rnaturalearth)

# Polygon
world = ne_countries(scale = "small", returnclass = "sf")
world = st_transform(world, "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
pol = world

# Make grid
grid = st_as_stars(st_bbox(pol), dx = 10000, dy = 10000)
grid = st_as_sf(grid)
grid = grid[pol, ]

grid = st_transform(grid, "+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")

st_write(grid,"data/grid/grid.shp", driver = "ESRI Shapefile")

I am now trying to merge it with information on population for each cell using the hyde data (https://dataportaal.pbl.nl/downloads/HYDE/HYDE3.2/baseline.zip).

I downloaded the bayseline hyde data and tried to apply the grid that I produced to the population data through an extract function that looks like this:


## use extract function for nightlights
shape <- rgdal::readOGR("data/grid/grid.shp")

source("scripts/extractfunction_hyde.R")
extract_hyde(directory = "data/hyde/hyde_harmonized", shape)

extract_hyde <- function(directory = ".", shp,
                          years = NULL) {
  require(raster)
  require(velox)
  
  #sname <- shpname 
  #shpname <- paste0("data/FDI/", shpname)
  #shp <- readRDS(shpname)
  
  if (!class(shp) %in% c("SpatialPolygons", "SpatialPolygonsDataFrame",
                         "SpatialPointsDataFrame")) {
    stop(paste("'shp' must be either a SpatialPolygons",
               "SpatialPolygonsDataFrame or SpatialPointsDataFrame"))
  }
  
  crs <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
  shp <- sp::spTransform(shp, sp::CRS(crs))
  
  orig.dir <- getwd()
  setwd(directory)
  
  files <- list.files(pattern = "*.asc$")
  
  # Years in which this population data are available:
  all.years <- as.numeric(substr(files, 6, 9))  # The year is characters 4 to 9
  
  # Need to average the years where there are two satellite readings:
  double.years <- all.years[duplicated(all.years)]
  
  # If years aren't provided, take all of them:
  if (is.null(years)) {
    years <- sort(unique(all.years))
  }
  
  # Start the output data.frame:
  if (class(shp) == "SpatialPolygons") {
    df <- data.frame(id = 1:length(shp@polygons))
  } else if (class(shp) == "SpatialPolygonsDataFrame") {
    df <- data.frame(shp@data)
  } else if (class(shp) == "SpatialPointsDataFrame") {
    df <- data.frame(shp@data)
  }
  
  for (i in seq_along(years)) {
    
    cat("Extracting  data for year ", years[i], "...", sep = "")
    
    # If there are two satellite readings in a year, average them first:
    if (years[i] %in% double.years) {
      both.files <- grep(years[i], files, value = TRUE)
      r  <- crop(raster(both.files[1]), shp, snap = "out")
      r2 <- crop(raster(both.files[2]), shp, snap = "out")
      values(r) <- (values(r) + values(r2)) / 2
      rm(r2)
      r <- velox(r)
      
      # With only one reading in a year, just read in the file normally:
    } else {
      r <- crop(raster(grep(years[i], files, value = TRUE)), shp, snap = "out")
      r <- velox(r)
    }
    
    extract <- r$extract(sp=shp, fun = function(x) mean(x, na.rm = TRUE))
    df[[paste0("pop_mean", years[i])]] <- c(extract)
    extract <- r$extract(sp=shp, fun = function(x) sum(x, na.rm = TRUE))
    df[[paste0("pop_sum", years[i])]] <- c(extract)

    
    
    cat("Done\n")
  }
  
  saveRDS(df, "data/hyde/hyde_grid.Rds")
}

Unfortunately, I get this error code:

         [,1]     [,2] [,3] [,4]
[1,] -9070131 -8626996  Inf  Inf
[2,] -9080131 -8626996  Inf  Inf
Error in .spTransform_Polygon(input[[i]], to_args = to_args, from_args = from_args,  :failure in Polygons 1584553 Polygon 1 points 3:4

The function works for all other shape files I worked with. For example, I followed the second option in the other stackoverflow post, and this works perfectly.

I researched and this problem sometimes ocured when there are different projections. But my function adjusts the projections of the hyde file and the shape file.

I assume I receive this error because the shp file was not produced correctly?

来源:https://stackoverflow.com/questions/64574446/extracting-data-from-raster-file-to-match-with-shp-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!