Counter-intuitive to all the other questions about splitting raster bands, I would like to split my single-band raster into a multiband raster stack based on the values given in each pixel (range from 1 to 11). Therefore, I would like to conditionally extract pixels based on their values and place them in an individual band. Basically:
band1 <- (if rastervalue == 1)
band2 <- (if rastervalue == 2)
.
.
.
band11 <- (if rastervalue == 11)
stacked <- stack(band1,band2,...band11)
writeRaster("path.tif")
Here is the overview of the data:
class : RasterLayer
dimensions : 25658, 15349, 393824642 (nrow, ncol, ncell)
resolution : 249.9999, 249.9999 (x, y)
extent : -15191755, -11354506, 8399516, 14814014 (xmin, xmax, ymin, ymax)
crs : +proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs
values : 1, 11 (min, max)
I have tried to do the following:
library(raster)
data <- raster("path.tif")
band1 = data[data != 1] = NA
band2 = data[data != 2] = NA
...
band11 = data[data != 11] = NA
stacked <- stack(band1,band2,...band11)
But, I get raster layers of NA for all the bands I create How can I do that in R?
data
when you dodata[data!=1]=NA
and then returns the value of that expression - not the new value ofdata
- to store intoband1
. And the value of that expression isNA
. You could do it by running in alocal
scope:band1 = local({data[data!=1]=NA;data})
which leaves the maindata
object unchanged. Or see my answer!