Intersection of bands in R raster package

巧了我就是萌 提交于 2019-12-06 21:28:27

I first proposed this:

x <- trim(inband, filename='fout')

But I now realize that would not get you what you want, as it would return the area (rows/columns) where at least one layer has a value that is not NA; rather than the area where all have a value that is not NA.

The below could be efficient. All cells with at least one NA value will become NA with sum (by default, na.rm=FALSE).

x <- sum(inband)
x <- trim(x)
r <- crop(inband, x)

perhaps followed by

r <- mask(r, x)

to set all cells in r to NA if they are NA in x

Thanks for the answers, they gave me good ideas. I came up with this, which is much faster:

myraster = stack(fn, bands) # You get the idea
NAvalue(myraster) = 0

# Tranform to 1 where there is data    
logical_raster = as.logical(myraster)

# Make a raster with 1 in the zone of intersection
a = subset(myraster, 1)
values(a) = TRUE
for(i in 1:nlayers(myraster)) {
  a = a & logical_raster[[i]]
}

# Apply the "mask" and trim to intersection extent
myraster = myraster * a
intersect_only = trim(myraster)

I discovered that all/any are the ways to do logical AND/OR on a long list. Here are demonstrated two identical plots that accomplish your goal on small rasters.

#dummy data
m1 = cbind(matrix(NA, nrow = 4, ncol = 2), matrix(1, nrow = 4, ncol = 2))
m2 = t(m1)
m3 = matrix(rep(c(1, NA), 8), nrow = 4)
inbands = stack(lapply(list(m1, m2, m3), raster))

# first method, using & operator 
plot(inbands[[1]] & inbands[[2]] & inbands[[3]])

# second method, using `all`
plot(all(inbands))

On my system there are warnings for coercing numeric to logical. The following two methods avoid the warnings but might be slower? They are logically equivalent but you might time them against each other and against the second method above.

plot(all(!is.na(inbands)))
plot(!any(is.na(inbands)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!