I have two slightly different solutions. The first requires you to manually determine the degree, but uses predefined functions. The second is more automatic, but a little manual.
Create a playable raster for which the first 2 lines are: NA
library(raster)
Decision No. 1
Manually get size from drawing using drawExtent ()
plot(r1) r1CropExtent <- drawExtent()
Crop the raster using the scale selected from the picture.
r2 <- crop(r1, r1CropExtent)
Land for comparison
layout(matrix(1:2, nrow=1)) plot(r1) plot(r2)
Decision number 2
It identifies the rows and columns of the raster that have only NA values ββand delete those that are on the border of the raster. Then it calculates the degree using extent() .
Convert the raster to a matrix that identifies whether the values ββare NA or not.
r1NaM <- is.na(as.matrix(r1))
Find columns and rows that are not completely filled with nAs
colNotNA <- which(colSums(r1NaM) != nrow(r1)) rowNotNA <- which(rowSums(r1NaM) != ncol(r1))
Find the size of the new raster using the first and last columns and rows that are not completely filled with NA. Use crop() to crop the new raster.
r3Extent <- extent(r1, rowNotNA[1], rowNotNA[length(rowNotNA)], colNotNA[1], colNotNA[length(colNotNA)]) r3 <- crop(r1, r3Extent)
Separate rasters for comparison.
layout(matrix(1:2, nrow=1)) plot(r1) plot(r3)