I'm trying to do some polygon/raster work in R. The extract function isn't working as I'd expect. Here's a reproducible example.
library(sf)
library(raster)
library(maptools)
raster <- download.file('https://raw.githubusercontent.com/JimShady/london_osm_canyons/master/test.tif', 'downloaded_raster')
raster <- raster('test.tif')
polygons <- read_sf('https://raw.githubusercontent.com/JimShady/london_osm_canyons/master/test2.geojson')
polygons <- st_transform(polygons, crs(raster)@projargs)
polygons$id <- 1
polygons <- as(polygons, 'Spatial')
new_polygon <- elide(polygons, rotate=-50)
proj4string(new_polygon) <- crs(raster)@projargs
polygons <- rbind(polygons, new_polygon)
plot(raster)
plot(polygons, add=T)
I want to get the number of cells that the each polygon intersects with, even if they are NA, and store them in the polygon as a column
polygons$cell_count <- extract(raster, polygons, fun = function(x,...)length(x), na.rm=F)
But this returns the number 5 for polygon one, when clearly the polygon intersects more than 5 cells of the raster. What's going on with that?
I then want to get the weighted mean. if there are any NA cells intersected, then this should 'fail' and return NA. I think this works, but as the above is wrong, I'm not very confident of my method now.
polygons$mean <- round(extract(raster, polygons, fun = mean, weights=T, na.rm=F),2)
I also want to know the number of cells that intersect that are less than one. I'm not sure how to do that. Anyone got a good idea?
polygons$almost_zero <-
Thanks for any help.