I want to add the extracted values from raster stack to the data.frame of the Spatial object using terra
package
f <- system.file("ex/logo.tif", package="terra")
r <- rast(f)
#Plot the raster
plot(r, 1:3)
#Create a vector file
points <- cbind.data.frame(Longitude = 40, Latitude = 40, val = 0.5)
points <- rbind.data.frame(points-1, points, points+1)
points_vect <- vect(points, geom=c("Longitude", "Latitude"), crs=crs(r, proj=T),
type = "points")
#Extract the values from raster using the point vector
terra::extract(r, points_vect, xy = T, method = "simple")
#> ID red green blue x y
#> 1 1 255 255 253 30 30
#> 2 2 149 159 186 40 40
#> 3 3 146 156 207 50 50
As you can see from the output val
filed is not there which we used to get using sp
aurgument of raster
package. Now how can I have the val
field added in the extracted data.frame?
Since terra::extract
extract values with the order of elements in the vector, you can simply cbind
the field to the extracted dataframe or add the needed field as a column with $
ex <- terra::extract(r, points_vect, xy = T, method = "simple")
ex$val <- points_vect$val
EDIT
The fastest option for extracting raster values is exact_extract
in the exactextract
package, which has an argument (called append_cols
) to attach the vector field to the data.frame resulting from the extraction.
exact_extract
accepts only polygon data (as sf
object) as input, but you can get around this by applying a buffer to your points and summarise the values. See the example below
library(exactextractr)
library(sf)
point_sf <- st_as_sf(points_vect)
point_sf <- st_buffer(point_sf,1)
ex <- exactextractr::exact_extract(stack(r),point_sf,fun="mean",append_cols="val")
#you can summarise values using a vector of functions
ex <- exactextractr::exact_extract(stack(r),point_sf,fun=c("mean","median","max","min"),append_cols="val")