### 1. Twinspan
wine<-read.csv("vineyards.csv")
summary(wine)
names(wine)
wine<-wine[,-1]


devtools::install_github("jarioksa/twinspan")
## Je treba instalovat Rtools (nabidne automaticky) a pak
## RESTARTOVAT R
## Pak znova spustit
devtools::install_github("jarioksa/twinspan")

library(twinspan)


tw.1<-twinspan(wine, levmax=4)
plot(tw.1)# Zobrazeni dendrogramu pro snimky
summary(tw.1)#Zobrazi summary klasifikace s pravidly urcujicimi rozdeleni snimku

plot(tw.1, what="sp")#Zobrazeni dendrogramu pro druhy
summary(tw.1, what="sp")#Zobrazi summary dendrogramu pro druhy

twintable(tw.1)# Zobrazi tabulku vyskytu a synoptickou tabulku s frekvencemi ve shlucich


cut(tw.1)# Zobrazi prislusnost vzorku k twinspan skupinam
cut(tw.1, level=1)# Totez, ale pouze pro prvni uroven rozdelovani

mod.tw.5<-cuth(tw.1, ngroups=5)# Slouci Twinspan skupiny do 5 shluku (provede modifikovany twinspan)

# Diagnostika pomoci silhouette plot
library(cluster)
library(vegan)
plot(silhouette(mod.tw.5, vegdist(sqrt(wine), method="chisq")))

# Zobrazeni klasifikace v DCA diagramu
dca.1<-decorana(sqrt(wine))
ordiplot(dca.1, type="n", display="si")
ordihull(dca.1, groups=mod.tw.5, col=1:5)
library(indicspecies)
summary(multipatt(sqrt(wine), mod.tw.5, duleg=T, func="r.g"))

### Isopam
library(isopam)


iso.1<-isopam(sqrt(wine), c.max=3, l.max=3, sieve=F)
plot(iso.1)# Zobrazeni dendrogramu
iso.1$flat# Zobrazeni klasifikaci na obou hiererchickych urovnich

iso.1$flat$level.2# Pouze druha uroven hierarchie

isotab(iso.1, level=2, phi.min=0.3)# Zobrazeni synopticke tabulky s relativnimi frekvencemi a Fisher-exact testem signifikance
plot(silhouette(iso.1$flat$level.2, vegdist(sqrt(wine))))#Silhoutte diagnostika

#Zobrazeni klasifikace v PCOA
pco.1<-capscale(sqrt(wine)~1, distance = "bray")
aa<-ordiplot(pco.1, displa="si", type="n")
ordihull(pco.1,groups=iso.1$flat$level.2, draw="poly", col=1:4)
points(aa, what="si", col=iso.1$flat$level.2, pch=16)
