2

I am using function unique() in package raster. I expect it to return the unique values for each layer, yet I get duplicated values... is that the expected result, or is there an issue somewhere?

library(raster)
#> Loading required package: sp
r <- raster(ncol=10, nrow=10)
r[] <- round(runif(ncell(r))*10)
s <- stack(r, as.integer(round(r/2)))

unique(s)
#> [[1]]
#>  [1]  0  1  2  3  4  5  6  7  8  9 10
#> 
#> [[2]]
#>  [1] 0 0 1 2 2 2 3 4 4 4 5
4

unique() returns the unique combinations of rows for all layers, similarly as the R base function unique() does on a data-frame.

If you want the unique values for each rows, separately, you could just use lapply() on the unstack() object:

lapply(unstack(s), unique)
#> [[1]]
#>  [1]  0  1  2  3  4  5  6  7  8  9 10
#> 
#> [[2]]
#> [1] 0 1 2 3 4 5
1

Matifou already explained why he got the answer he got. Here are two alternative approaches (very similar)

library(raster)
r <- raster(ncol=10, nrow=10)
values(r) <- round(runif(ncell(r))*10)
unique(r)
# [1]  0  1  2  3  4  5  6  7  8  9 10

Unique values for a multi-layer object

s <- stack(r, round(r/2), round(r/3))
u <- unique(s)

Unique combinations

do.call(rbind, u)
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#[1,]    0    1    2    3    4    5    6    7    8     9    10
#[2,]    0    0    1    2    2    2    3    4    4     4     5
#[3,]    0    0    1    1    1    2    2    2    3     3     3

Unique by layer

lapply(u, unique)
#[[1]]
# [1]  0  1  2  3  4  5  6  7  8  9 10
# 
#[[2]]
#[1] 0 1 2 3 4 5
# 
#[[3]]
#[1] 0 1 2 3

or

lapply(1:nlayers(s), function(i) unique(s[[i]]))
#[[1]]
# [1]  0  1  2  3  4  5  6  7  8  9 10
#
#[[2]]
#[1] 0 1 2 3 4 5
#
#[[3]]
#[1] 0 1 2 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.