1

I have a .shp file (2 columns: Total population and POLYGON objects as geometry) and I want to convert it into a .tif file. How can I do it in Python or R?

My shapefile

MarFat
  • 11
  • 2
  • https://stackoverflow.com/questions/35096133/converting-shapefile-to-raster Maybe this helps? – Zoe Jul 28 '21 at 13:50
  • The `sf` package in R is good. This will probably tell you how to convert that shp file to a tif file. https://geocompr.robinlovelace.net/read-write.html – Tob Jul 28 '21 at 13:50

1 Answers1

0

here an example with toy data:

library(terra)
library(raster)
library(fasterize)
library(sf)
library(microbenchmark)

cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
cds3 <- rbind(c(70,0), c(10,60), c(10,0), c(10,-55), c(70,0))
polys <- spPolygons(cds1, cds2,cds3)
polys$total_pop <- c(10,50,100)

base_raster <- raster(polys,resolution=c(10,10))
values(base_raster) <- 1:ncell(base_raster)
plot(base_raster)

microbenchmark(raster=p1 <- raster::rasterize(polys,base_raster,field="total_pop"),
terra=p2 <- terra::rasterize(vect(polys),rast(base_raster),field="total_pop")
)
plot(p1)
plot(p2)

if you have a .shp file, just read it in R with:

#if you want to use raster::rasterize
polys <- shapefile("path/of/your/shapefile")

#if you want to use terra::rasterize
polys <- vect("path/of/your/shapefile")
Elia
  • 2,210
  • 1
  • 6
  • 18