Search code examples
rrasterr-rasterterra

Problem using terra::extract results present nan value


I would like to extract values from rasters to points. I am using the terra and extract() function. The script works but I noticed that for some rows (about 100) the result of the extract function is the value "nan". No points are outside rasters. I have this problem also adding the na.rm=T option. If I try to do the same operation using as example qgis I don't have this problem. How is it possible? Has anyone ever encountered this problem?


Solution

  • Start by plotting the points (SpatVector y) on the raster (SpatRaster x)

    plot(x)
    points(y)
    

    If that does not look good, you should probably do

    y <- project(y, crs(x))
    

    (perhaps QGIS does that for you?)

    Otherwise, to find out where this happens, you could select those points, perhaps like this:

    e <- extract(x, y, xy=TRUE)
    yna <- y[is.na(e[,names(x)[1]]), ]
    plot(x)
    points(yna) 
    

    And now zoom in to one or more of these points

    zoom(x) # click twice on the map
    points(yna) 
    

    You can save these points to disk with writeVector(yna, "points.shp") so that you can compare again with QGIS.

    And, by the way, extract does not have argument na.rm (see ?extract)