# r raster: unique returns duplicated values?

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)
r <- raster(ncol=10, nrow=10)
r[] <- round(runif(ncell(r))*10)
s <- stack(r, as.integer(round(r/2)))

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

`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)
#> []
#>    0  1  2  3  4  5  6  7  8  9 10
#>
#> []
#>  0 1 2 3 4 5
``````

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)
#   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)
#[]
#   0  1  2  3  4  5  6  7  8  9 10
#
#[]
# 0 1 2 3 4 5
#
#[]
# 0 1 2 3
``````

or

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