I am trying to extract bioclimatic variables from individual grid cells. So i started loading my shapefile:
# I used the Admin 0 - Countries (1:10) dataset from Natural Earth
shp <- sf::st_read(""ne_10m_admin_0_countries.shp"")
shape <- as_Spatial(shp)
crs <- "+proj=longlat +ellps=WGS84 +datum=WGS84"
proj4string(shape) = crs
I used spsample() and HexPoints2SpatialPolygons() to create a hexagonal grid based on my shape object, and then I intersected the grid and the polygon.
size <- 0.5 #0.5 degrees
hex_points <- spsample(shape, type = "hexagonal", cellsize = size)
hex_grid <- HexPoints2SpatialPolygons(hex_points, dx = size)
shape.grid <- gIntersection(shape, hex_grid, byid = T)
I load my points (646) and plotted then on my new shapefile: *Note that some of my points have the same coordinates.
coords <- read.table("clipboard", header=T)
coords$lat <- as.numeric(coords$lat)
coords$long <- as.numeric(coords$long)
coordinates(coords) <- ~long + lat
prj<-'+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0'
coords <- SpatialPoints(coords, proj4string = CRS(prj))
proj4string(coords)<-proj4string(shape.grid)
Then I selected the grid cells which have points on (261): And here I am getting some problems.
shape.grid.containing.points <- shape.grid[coords, ]
bio10 <- raster(choose.files()) #[Bioclimatic variable][3] from WorldClim
bio10 <- extract(x=bio10, y=shape.grid.containing.points, fun=mean, cells = T)
Indeed I was able to extract variables from the grid cells i was aiming. However, the number of grid cells is smaller than the number of points, and I dont know which points were ommited because they where in the same grid or have the same coordinate.
How do I have a data frame with all of my points (646 lines) and the value of the variable I extract from the grid cell, instead of a data frame with only 261?