Search code examples
rrasterr-spterra

select points over land area in R


I have a point vector for the entire globe at 0.25 degree resolution.

library(terra)
library(rnaturalearth)

# create point data 
ref_grid <- terra::ext(-180, 180, -90, 90)
ref_grid <- terra::rast(ref_grid)
res(ref_grid)<- 0.25
values(ref_grid)<-1 #dummy values

projections <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
crs(ref_grid) <- projections
pts <- terra::as.points(ref_grid, values=TRUE, na.rm=TRUE)  

# download world shapefile
world_shp <- rnaturalearth::ne_countries()
world_shp <- terra::vect(world_shp)
world_shp <- terra::project(world_shp, projections)

I want to extract those points that fall within a landmass i.e. remove all those points that are in the ocean. So I did this:

e <- terra::extract(world_shp, pts)

But it's been two hours now and this is still running. Is there any faster way to do this?


Solution

  • You should not transform raster data to vector data if you want efficiency. In this case, you can do the following in a second or so:

    library(terra)
    library(rnaturalearth)
    ref_grid <- terra::rast(res=0.25)
    world_shp <- rnaturalearth::ne_countries(returnclass="sf") |> vect()
    
    ref_grid <- rasterize(world_shp, ref_grid)
    p <- as.points(ref_grid)
    

    (but perhaps, depending on what you do next, the last step should also be avoided)