Skip to content

Instantly share code, notes, and snippets.

@bniebuhr
Created February 23, 2022 00:14
Show Gist options
  • Save bniebuhr/41c2bf318a3eead01ac0e9598f1e1811 to your computer and use it in GitHub Desktop.
Save bniebuhr/41c2bf318a3eead01ac0e9598f1e1811 to your computer and use it in GitHub Desktop.
Ways to create buffers and extract values from raster in R
# packages
library(dplyr)
library(landscapemetrics)
library(sf)
library(terra)
# Load data - Latlon, WGS84,
forest_1985 <- raster::raster("data/mapbiomas_v06_1985_forest.tif")
# CRS
crs_atlantic <- raster::crs(forest_1985)
# resolution of the map in degrees and meters
res_orig <- raster::res(forest_1985)[1]
res_m <- 30
# Create points
points <- sf::st_as_sf(data.frame(x = c("-39.48", "-41.35"), y = c("-12.85", "-12.98")),
coords = c("x", "y"),
crs = crs_atlantic)
# parameters
buffer_size <- 5000 # in meters
# Create buffers - construct buffers function from landscapemetrics
y <- landscapemetrics::construct_buffer(pol, shape = "circle", size = buffer_size*res_orig/res_m)
plot(y[1], col = 2)
landscape <- forest_1985
current_plot <- 1
landscape_crop <- raster::crop(x = landscape,
y = y[current_plot])
landscape_mask <- raster::mask(x = landscape_crop,
mask = y[current_plot])
plot(landscape_mask)
# Create buffers - sf package
units(buffer_size) <- "meter"
y2 <- pol %>% sf::st_buffer(pol, dist = buffer_size) %>% as("Spatial")
plot(y[1], col = 2)
plot(y2[1,], col = grey(level = 0.5, alpha = 0.5), add = T)
# Create buffers - terra package
y3 <- points %>% terra::vect() %>% terra::buffer(width = buffer_size)
plot(y[1], col = 2)
plot(y3[1], col = grey(level = 0.5, alpha = 0.5), add = T)
landscape_crop <- terra::crop(x = terra::rast(landscape),
y = y3[current_plot])
landscape_mask <- terra::mask(x = landscape_crop,
mask = y3[current_plot])
plot(landscape_crop)
plot(landscape_mask)
lsm_c_enn_mn(landscape_mask)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment