1
votes

I need to create random points inside a polygon and then extract the information related to the point from a raster. But I have an error with the function extract(). I try to transform the random points file to a SpatialPoints, but when I try this I have the same error:

Error in (function (classes, fdef, mtable): unable to find an inherited method for function ‘extract’ for signature ‘"RasterLayer", "sfc_POINT"’

my skript is:

    map <- raster("/home.../mosaic.tif")
    #class      : RasterLayer 
    #dimensions : 30734, 52746, 1621095564  (nrow, ncol, ncell)
    #resolution : 1, 1  (x, y)
    #extent     : 367836.4, 420582.4, 5805983, 5836717  (xmin, xmax, ymin, ymax)
    #crs        : +proj=utm +zone=33 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
    #source     : /home/.../mosaic.tif 
    #names      : mosaic 
    #values     : 0, 65535  (min, max)
    #EPSG:32632

    pol <- st_read("/home/.../polygon_without_buldings.shp")
    #Reading layer `polygon_without_buldings_tegel' from data source `/home/.../polygon_without_buldings_tegel.shp' using driver `ESRI Shapefile'
    #Simple feature collection with 4 features and 2 fields
    #geometry type:  MULTIPOLYGON
    #dimension:      XY
    #bbox:           xmin: 383943.5 ymin: 5827189 xmax: 384882.8 ymax: 5828116
    #CRS:            32633


    #transform the polygon to map's crs EPSG:32632
    pol <- st_transform(pol, crs = 32632)
    #Simple feature collection with 4 features and 2 fields
    #geometry type:  MULTIPOLYGON
    #dimension:      XY
    #bbox:           xmin: 790333.1 ymin: 5834483 xmax: 791275.4 ymax: 5835389
    #CRS:            EPSG:32632
    #id id_2                       geometry
    #1 1000   NA MULTIPOLYGON (((790333.1 58...
    #2    1   NA MULTIPOLYGON (((790528.6 58...#

    rp <- st_sample(pol, size =100, type='random')
    #Geometry set for 100 features 
    #geometry type:  POINT
    #dimension:      XY
    #bbox:           xmin: 790397.7 ymin: 5834492 xmax: 791188.3 ymax: 5835357
    #CRS:            EPSG:32632
    #First 5 geometries:

    rp_sp<-SpatialPoints(rp, proj4string=CRS(map@crs))

    buffer <- extract(map, rp, buffer=10.5, fun=mean)
    #Error in (function (classes, fdef, mtable)  : 
    #unable to find an inherited method for function ‘extract’ for signature ‘"RasterLayer", "sfc_POINT"’

Maybe is some basic error, but I'm new with spatial data with R. Thanks in advance for your help.

1

1 Answers

1
votes

Please always include a minimal, reproducible, self-contained example when you ask a R question. Like this

library(raster)
library(sf)
p <- shapefile(system.file("external/lux.shp", package="raster"))
s <- as(p, "sf")
r <- raster(p, ncol=100, nrow=100)
values(r) <- 1:ncell(r)

There are different solutions, but one thing you can do is this

rp <- st_sample(s, size =100, type='random')
sp <- as(s, "Spatial")
buffer <- extract(r, sp, buffer=0.1, fun=mean)