Marcos
Marcos

Reputation: 123

How to use values in a raster object to create layers?

I have a raster object containing different values in each cell, like in the example below:

library(raster)
x <- matrix(1:5,nrow = 5, ncol = 1)
r <- raster(x)
plot(r)

r
> r
class      : RasterLayer 
dimensions : 5, 1, 5  (nrow, ncol, ncell)
resolution : 1, 0.2  (x, y)
extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : memory
names      : layer 
values     : 1, 5  (min, max)

Ploted raster with one layer

I would like to know if there is an easy way to create new layers based on the values of the raster, preserving its spatial structure.

I managed to do that manually in the example below, but I reckon that is not an effective way to do that if you have several values to transform into layers.

l1 <- r
l2 <- r
l3 <- r
l4 <- r
l5 <- r

values(l1)[which(values(r)!=1)] <- 0
values(l2)[which(values(r)!=2)] <- 0
values(l3)[which(values(r)!=3)] <- 0
values(l4)[which(values(r)!=4)] <- 0
values(l5)[which(values(r)!=5)] <- 0

r1 <- stack(l1,l2,l3,l4,l5)
plot(r1)

r1
> r1
class      : RasterStack 
dimensions : 5, 1, 5, 5  (nrow, ncol, ncell, nlayers)
resolution : 1, 0.2  (x, y)
extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
crs        : NA 
names      : layer.1, layer.2, layer.3, layer.4, layer.5 
min values :       0,       0,       0,       0,       0 
max values :       1,       2,       3,       4,       5 

Raster with layered values

Any help is appreciated!

Thanks

Upvotes: 1

Views: 215

Answers (2)

Robert Hijmans
Robert Hijmans

Reputation: 47536

There is a method for that

x <- layerize(r)

But the layers are 0 / 1 (FALSE/TRUE) as you can see below.

x
# (...)
#names      : X1, X2, X3, X4, X5 
#min values :  0,  0,  0,  0,  0 
#max values :  1,  1,  1,  1,  1 

To get the original numbers back, you could do

x <- layerize(r) * unique(r) 

Or perhaps the more explicit

u <- unique(r)
x <- layerize(r, classes=u) * u 

x
# (...)
#names      : X1, X2, X3, X4, X5 
#min values :  0,  0,  0,  0,  0 
#max values :  1,  2,  3,  4,  5 

Upvotes: 2

Allan Cameron
Allan Cameron

Reputation: 174478

Yes, you can achieve this in a single line:

r1 <- stack(lapply(unique(r[]), function(i) {r[r[] != i] <- 0; r;}))

So that

plot(r1)

enter image description here

Upvotes: 2

Related Questions