####KORELACE-------------------

head(ext)
head(forest)

cor(ext$Altitude, ext$Temperature, method = "pearson")
cor.test(ext$Altitude, ext$Temperature, method = "pearson")

cor.mat <- cor(ext)

library(corrplot)
library(viridis)

corrplot.mixed(cor.mat, lower = "number", upper="square",
               tl.pos = "lt", tl.cex=0.7, tl.col="black",
               number.cex=0.7, title="Correlation matrix",
               upper.col=rev(plasma(100)), lower.col=viridis(100))

plasma(4)
rev(plasma(4))

my.col <- colorRampPalette(c("blue", "yellow", "red3"))
my.col(5)

corrplot.mixed(cor.mat, lower = "number", upper="square",
               tl.pos = "lt", tl.cex=0.7, tl.col="black",
               number.cex=0.7, title="Correlation matrix",
               upper.col=rev(my.col(100)), lower.col=viridis(100))

cor(forest$Diversity, ext$Altitude)
cor.test(forest$Diversity, ext$Altitude)

cor.tab <- cor(ext, forest$Diversity)
abs(cor.tab)> 0.1

rownames(cor.tab)[abs(cor.tab[,1])> 0.1]

cor.tab[abs(cor.tab[,1])> 0.1,]

summary(ext)

hist(forest$Diversity)
hist(log(forest$Diversity))

shapiro.test(forest$Diversity)

hist(ext$Altitude)

cor(forest$Diversity, ext$Forest)
cor(forest$Diversity, log1p(ext$Forest))

plot(ext$ForestAB, forest$Diversity)
l <- loess.smooth(ext$ForestAB, forest$Diversity)
lines(l, lwd=3, col="red")

###regrese
m <- lm(forest$Diversity ~ Limestone.and.calcareous.sediments, data=ext)
m
anova(m)  
summary(m)

plot(ext$Limestone.and.calcareous.sediments, forest$Diversity,
     xlab="Proportion of linestones (%)", ylab="No. of species",
     las=1, cex.lab=1.5, cex.axis=1.5, pch=21, bg="gray",
     cex=1.5, lwd=1)
grid()
abline(m, lwd=3, col="red")
box(lwd=2)

ms <- summary(m)
R2 <- ms$adj.r.squared
p <- pf(ms$fstatistic[1],
        ms$fstatistic[2],
        ms$fstatistic[3], lower.tail = FALSE)

text(0.5, 19, paste("R2 =", round(R2,1), ", p =", round(p, 3)),
     pos=4, cex=1.5)

a <-coef(m)[1]
b <- coef(m)[2]

text(0.5, 21, paste("y =", round(a,1), "+", round(b, 1), "* x"),
     pos=4, cex=1.5)

###model2

m2 <- lm(forest$Diversity ~ ., data = ext)
m2
summary(m2)


m3 <- lm(forest$Diversity ~ ForestAB + Limestone.and.calcareous.sediments, 
        data=ext)
summary(m3)

library(adespatial)

fs <- forward.sel(Y=as.data.frame(forest$Diversity), X=ext)
fs
fs$variables

m3 <- lm(forest$Diversity ~ ., data=ext[, fs$variables])
summary(m3)

##rozklad var

clim <- c("Temperature", "Precipitation")
geo <- c("Carpathian.flysch.sediments", "Cretaceous.sediments",
         "Limestone.and.calcareous.sediments", "Proterozoic.and.Palaeozoic.rocks",
         "Upper.Tertiary.and.Quaternary.sediments")
lc <- c("Arable.land", "Forest", "ForestAB")

library(vegan)
vp <- varpart(Y = as.data.frame(forest$Diversity),
              ext[,clim], ext[,geo[c(1,5)]], ext[,lc])
vp
plot(vp)

