### 1 
wine<-read.csv("vineyards.csv")
summary(wine)


# Odstraneni jednotlivych vyskytu
wine<-wine[,(colSums(wine>0)>1)]

## a - Hellinger
library(vegan)
wine.h<-vegdist(decostand(wine, method="hell"), method="eucli")

wine.k<-kmeans(wine.h, centers=3)

k=2
library(cluster)
sw<-NA

for (k in 2:10){
  km<-kmeans(wine.h, centers=k)
  sw.temp<-summary(silhouette(km$cluster, wine.h))
  sw[k]<-sw.temp$avg.width
}

plot(sw, type='h')

wine.k<-kmeans(wine.h, centers=8)


## Klastrová analýza
wine.cl<-hclust(wine.h, method="ward.D")
plot(wine.cl)

sw<-NA
k=2

for (k in 2:20){
  hcut<-cutree(wine.cl, k=k)
  sw.temp<-summary(silhouette(hcut, wine.h))
  sw[k]<-sw.temp$avg.width
}
sw

plot(sw, type='h')

hcut<-cutree(wine.cl, k=9)

plot(wine.cl)
rect.hclust(wine.cl, k=9)


#### Bray - Curtis přístup
wine.b<-vegdist(sqrt(wine), method="bray")

#PAM
sw<-NA
?pam
for (k in 2:10){
  pm<-pam(wine.b, k=k)
  sw.temp<-summary(silhouette(pm$cluster, wine.b))
  sw[k]<-sw.temp$avg.width
}

plot(sw, type='h')
pm<-pam(wine.b, k=5)




## Klastrová analýza
wine.clb<-hclust(sqrt(wine.b), method="ward.D")
# wine.clb<-hclust(sqrt(wine.b), method="single")
# wine.clb<-hclust(sqrt(wine.b), method="complete")
# wine.clb<-hclust(sqrt(wine.b), method="average")

plot(wine.clb)

sw<-NA
k=2

for (k in 2:20){
  hcut.b<-cutree(wine.clb, k=k)
  sw.temp<-summary(silhouette(hcut.b, wine.b))
  sw[k]<-sw.temp$avg.width
}
sw

plot(sw, type='h')

hcut.b<-cutree(wine.cl, k=6)

plot(wine.clb)
rect.hclust(wine.clb, k=6)

### Diagnostika
plot(silhouette(wine.k$cluster, wine.h), col=1:8)
plot(silhouette(hcut, wine.h), col=1:9)
plot(silhouette(pm, wine.b), col=1:5)
plot(silhouette(hcut.b, wine.b), col=1:6)


#Zobrazeni v ordinacnim diagramu
# k-means
pca.1<-rda(decostand(wine, method="hell")~1)

aa<-ordiplot(pca.1, display="si", type='n')
ordihull(pca.1, groups=wine.k$cluster, 
         draw="poly", col=1:8, lty=0)
points(aa, col=wine.k$cluster, pch=16)

# PAM
pco.1<-capscale(wine.b~1)
aa<-ordiplot(pco.1, display="si", type='n')
ordihull(pco.1, groups=pm$clustering, 
         draw="poly", col=1:5, lty=0)
points(aa, what="si", col=pm$clustering, pch=16)


#Popis klastru







