Here I demonstrate how to generate k-means output from stacked raster data in R
. For the .Rmd behind this output, right click, copy the link and paste in your browser my gitHub account.
I will make use of worldclim data and global administrative units data of Kenya.
my_rasters <- getData('worldclim', res = 10, var = 'tmin')
my_polygon <- getData('GADM', country = 'KEN', level = 0)
masked_rasters <- mask(crop(my_rasters, my_polygon), my_polygon)
plot(masked_rasters[[2]])
stacked_rasters <- raster::stack(masked_rasters)
Running k-means on raster data requires use of raster.kmeans
function in ecbtools
package. To install the ecbtools
package use:
remotes::install_github(“ozjimbob/ecbtools”)
You may need to install remotes
package first to have the install_github
function.
kmeans_layer <- ecbtools::raster.kmeans(x = stacked_rasters, # The stack
k = 4,# Number of clusters
nstart = 3, # random sets
geo = TRUE, # weighting by location (x,y coords)
geo.weight = 1) # wweight to location
raster::plot(kmeans_layer)
Saving the raster into the current working directory for future reference or subsequent analysis/sharing as need may be.
raster::writeRaster(kmeans_layer, 'output_clusters.tif', overwrite = TRUE)