如何找到两个栅格对象的交集?
e1 = extent(0, 10, 0, 10) #xmin, xmax, ymin, ymax
s1 = raster(e1, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e2 = extent(0, 12, 3, 10) #xmin, xmax, ymin, ymax
s2 = raster(e2, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e3 = extent(24, 50, 40, 50) #xmin, xmax, ymin, ymax
s3 = raster(e3, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
答案 0 :(得分:0)
以下代码应该有效。它还处理了一些奇怪的错误。
library(raster)
library(sp)
# define rasters
e1 = extent(0, 10, 0, 10) #xmin, xmax, ymin, ymax
s1 = raster(e1, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e2 = extent(0, 12, 3, 10) #xmin, xmax, ymin, ymax
s2 = raster(e2, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e3 = extent(24, 50, 40, 50) #xmin, xmax, ymin, ymax
s3 = raster(e3, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
test_intersection <- function(a,b){
#reads in two rasters and tests for overlap T or F
# if returns TRUE then there is overlap
if(class(a)!='Extent'){ a = extent(a)}
if(class(b)!='Extent'){ a = extent(b)}
!class(try(intersect(a,b),T ))=='try-error'}
# Test function
intersect(e1,e2)library(raster)
library(sp)
# define rasters
e1 = extent(0, 10, 0, 10) #xmin, xmax, ymin, ymax
s1 = raster(e1, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e2 = extent(0, 12, 3, 10) #xmin, xmax, ymin, ymax
s2 = raster(e2, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
e3 = extent(24, 50, 40, 50) #xmin, xmax, ymin, ymax
s3 = raster(e3, nrows=10, ncols=10, crs=CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'))
test_intersection <- function(a,b){
#reads in two rasters and tests for overlap T or F
# if returns TRUE then there is overlap
# try error is included b/c errors has come up with other test data
!(class(try(intersect(a,b),T ))=='try-error' | is.null(intersect(a,b)))
}
# Test function
intersect(e1,e2)
test_intersection(e1,e2)
intersect(e1,e3)
test_intersection(e1,e3)
test_intersection(e1,e2)
intersect(e1,e3)
test_intersection(e1,e3)