Set up

Make sure you install and load the required packages. Remember to use help() when you have questions about specific functions. This quiz will focus only on unsupervised classification.

library("sp")
## Warning: package 'sp' was built under R version 3.4.3
library("raster")  
## Warning: package 'raster' was built under R version 3.4.3
library("cluster")

Load the results of the unsupervised classification (kmeans.RDS) we worked through in the tutorial. You’ll also need to load the Sentinel image from the tutorial (unclipped version) so you can complete the classification and plot the results in Question 4.

k.classification <- readRDS("C:/Users/Maggie/Downloads/kmeans.RDS")
Sentinel.img = stack("C:/Users/Maggie/Downloads/tutorial/Sentinel2_20160605_10m.img")
Sentinel.matrix <- getValues(Sentinel.img)

Q1

k.classification$size[3]
## [1] 156178

Q2

k.classification$centers[12,4]
## [1] 2882.082

Q3

k.classification$cluster[1]
## [1] 12

Q4

# Hint:  Don't forget to use Sentinel.matrix to create the Sentinel.remove object to remove NAs from the kmeans_raster:
Sentinel.matrix <- getValues(Sentinel.img)
Sentinel.remove <- which(!is.na(Sentinel.matrix)) # Select all the pixel with values different to NA
Sentinel.matrix <- na.omit(Sentinel.matrix)# the function na.omit() returns the #object with incomplete cases removed
#create a raster according to the Sentinel image
kmeans_raster = raster(Sentinel.img)
# add the classification for each pixel to the raster, remove pixels with NA values
kmeans_raster[Sentinel.remove] <- k.classification$cluster 
plot(kmeans_raster)