EDIT 2: I provide a shorter version based on extract
function from the raster
package.
library(raster)
library(sp) # used to create a SpatialPoint object
# LOAD RASTERS INTO A LIST OBJECT.
tmp <- lapply(list.files("D:/rasters", pattern = ".tif$", full.names = TRUE), raster)
# A DATA FRAME WITH THE FOLLOWING STRUCTURE IS REQUIRED
coords <- data.frame("lat" = c(-2.2, -13.76, 4.47), "lon" = c(5.97, 10.57, 8.7))
# NEW CODE STARTS HERE
pts <- SpatialPoints(coords = coords,
proj4string = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "))
# THE NEXT LINE PROVIDES THE SAME OUTPUT AS THE FOLLOWING LONG CODE
as.data.frame(cbind(coords, do.call("rbind", lapply(tmp, extract, pts))))
I provide a generalized answer by making usage of a raster
library functionality. It can be used to process multiple raster files and multiple lat-lon pairs.
The main idea is to use cellFromXY
to get the cell index for a specific lat-lon pair. Then just extract the value using r[cellIndex]
, when r
is a raster object.
This is given for a data frame with one row - i.e. only one pair of lat-lon, but you can easily wrap it with another lapply
combined with rbind
to iterate it over multiple lat-lon pairs.
EDIT: now you can run the code using multiple lat-lon points. Note that the input data.frame
structure should be kept.
library(magrittr) # I used piping in my answer (%>%)
library(raster) # raster functionality in r
# Assuming my .tif files are in this path: "D:/rasters"
# LOAD RASTERS INTO A LIST OBJECT.
tmp <- lapply(list.files("D:/rasters", pattern = ".tif$", full.names = TRUE), raster)
# A DATA FRAME WITH THE FOLLOWING STRUCTURE IS REQUIRED
coords <- data.frame("lat" = c(-2.2, -13.76, 4.47), "lon" = c(5.97, 10.57, 8.7))
# RUN THE FOLLOWING TO GET A MATRIX WITH VALUES
cellData <- lapply(tmp, function(r) {
apply(coords, MARGIN = 1, FUN = function(row) {
# as.matrix(coords[row, c("lat", "lon")]) # print(row)
cellIndex <- cellFromXY(r, row) # gives cell Index for lat/lon pair
r[cellIndex]
})
}) %>% do.call("cbind", .)
# BIND MATRIX AS A DATA FRAME
output <- as.data.frame(cbind(coords, cellData))
Finally my result for 3 rasters and 3 points looks like this: