Skip to content

error occured when combining st_sample() with raster::extract()

3 messages · Bede-Fazekas Ákos, Xiang Ye

#
Dear community,

I am exploring the functionality of raster package by following the online textbook Geocomputation with R, 1st ed. (I know the newer version of the textbook is online, I just want to finish what I left). The problem I encountered is associated with the example from Section 5.4.2, raster extraction:
https://bookdown.org/robinlovelace/geocompr/geometric-operations.html#raster-extraction
When I want to combine it with st_sample() from Section 5.2.3, i.e. extract the pixel values from say 15 randomly chosen locations, I met an error.

Here comes the script:

library(sf)
library(raster)

filename=system.file('raster/srtm.tif', package='spDataLarge')
srtm=raster(filename)
filename=system.file('vector/zion.gpkg', package='spDataLarge')
zion=st_read(filename)
zion=st_transform(zion, projection(srtm))

data('zion_points', package='spDataLarge')
extract(srtm, zion_points) # textbook example, work as expected

sampled_sites=st_sample(zion, 15)
extract(srtm, sampled_sites) # error occurred.

The error message says "????: ??????extract???????x = "RasterLayer", y = "sfc_POINT"?????????????"
There is Chinese text embedded because my OS is in Chinese. Translated into English, it reads "ERROR: function 'extract' labelling ??x = "RasterLayer", y = "sfc_POINT"?? cannot find the inherited methods".

My question: what's the reason of this problem, and how to fix it?

Thank you in advance!

??? YE, Xiang
THINKING SPATIALLY<http://www.linkedin.com/in/spatialyexiang>.
Ph.D. in Spatial Statistics
#
Dear Xiang,

I guess that the reason for the error is that zion_points is an sf 
object, while sampled_sites is an sfc object. You should create a 
0-column sf object from the sfc using function st_as_sf().
Please try the following code:
extract(srtm, st_as_sf(sampled_sites))

HTH,
?kos
__________
?kos Bede-Fazekas
Centre for Ecological Research, Hungary


2024. 06. 23. 19:24 keltez?ssel, Xiang Ye via R-sig-Geo ?rta:
#
Dear ?kos,

Thank you so much for the swift reply! Your answer helped me to solve this issue perfectly.
Have a great one!

?? YE, Xiang
THINKING SPATIALLY<http://www.linkedin.com/in/spatialyexiang>.
Ph.D. in Spatial Statistics