I have multiple raster TIF files. I'm using R and want to extract a cell's attribute value from all rasters based on an latitude and longitude input, and saved in a single CSV file. The output should be formatted as follows:
Lat Long Value* Value**
20.15 77.12 12 20
* denotes attribute values from raster 1.
** denotes attribute values from raster 2.
Can anyone help me in this?
Best Answer
EDIT 2: I provide a shorter version based on
extract
function from theraster
package.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 usingr[cellIndex]
, whenr
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 withrbind
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.Finally my result for 3 rasters and 3 points looks like this: