[RS-ecology] Problems with kmeans

Benjamin Leutner benjamin.leutner at uni-wuerzburg.de
Wed Nov 20 13:17:30 CET 2019


Hi Danilo,

the issue here are NAs in the input data, which the kmeans algorithm 
can't deal with.
If you do it "by hand" you'll need to exclude NAs  (see example below).
Note that in practice, it is recommendable to use 
RStoolbox::unsuperClass(), which takes care of NA handling and will also 
work if your raster is too big to fit into memory.


## Example: K-Means with NAs
library(raster)
data(lsat)

## setup empty output raster
output   <- raster(lsat)
output[] <- NA

## load all values into matrix
values <- lsat[]

## Identify pixels which have valid values in all bands
valid <- complete.cases(values)

## Cluster only complete pixels
km <- kmeans(values[valid,], centers = 5)

## Turn matrix into raster
output[valid] <- km$cluster
plot(output)


Best regards,
Benjamin

On 31.10.19 18:04, Danilo Procaccini wrote:
> Dear RS-ecology community,
> I am practicing with the exercises proposed in the book.
> At page 178
> launching the command
> p224_r63_2011.kmeans <- kmeans (p224r63_2011_sub[], centers =5, 
> iter.max = 100, nstart = 10)
> i receive the error Error in do_one(nmeth) :   NA/NaN/Inf |inforeign 
> functioncall| (arg 1)
> I loaded the raster from data_book/raster_data/final/p224r63_2011.grd 
> with the command brick as shown in the book
> and then i launched the command p224r63_2011_sub <- p224r63_2011[[c(1:4]]
> any solutions?
> Best regards,
> Danilo Procaccini
>
> _______________________________________________
> RS-ecology mailing list
> RS-ecology at lists.uni-wuerzburg.de
> https://lists.uni-wuerzburg.de/mailman/listinfo/rs-ecology

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.uni-wuerzburg.de/pipermail/rs-ecology/attachments/20191120/693865b6/attachment.html>


More information about the RS-ecology mailing list