
###### NB: On inclusion of the shiny function, the "Run" disappears. so use CTRL + ENTER to run codes.


# Set the working directory

setwd("D:/Mentorship/Carbon")


# Packages

# install.packages("car")
# install.packages("effects", dependencies = T)
# install.packages("compute.es")
# install.packages("ggplot2")
# install.packages("multcomp")
# install.packages("pastecs")
# install.packages("reshape")
# install.packages("Hmisc")


# Installing the WRS package from R-Forge:

# Step 1: Install dependent packages:
install.packages(c("MASS", "akima", "robustbase"), dependencies = T)

# Step 2: Install suggested packages:
install.packages(c("cobs", "robust", "mgcv", "scatterplot3d", "quantreg", "rrcov", "lars", "pwr", "trimcluster", "parallel", "mc2d", "psych", "Rfit"), dependencies = T)

# Step 3: install WRS:
install.packages("WRS", repos="http://R-Forge.R-project.org", type="source")


# Initiate packages
library(car)
library(compute.es)
library(effects)
library(ggplot2)
library(multcomp)
library(pastecs)
library(reshape)
library(WRS2)
library(Hmisc)


#--------Carbon data----------
# We are interested in the effects of Grazing mgt,	Land cover type, and	Soil depth on MAOC and POC.

# We are also interested in whether this effect was different across different Slope positions.


CarbonData <- read.csv("CarbonData.csv")
head(CarbonData)

str(CarbonData)

# Making factors
CarbonData$Grazing.mgt <- as.factor(CarbonData$Grazing.mgt)
CarbonData$Slope.position <- as.factor(CarbonData$Slope.position)
CarbonData$Land.cover.type <- as.factor(CarbonData$Land.cover.type)
CarbonData$Soil.depth <- as.factor(CarbonData$Soil.depth)


# Exploring the data

# To explore the effects of Grazing management, land cover type, and soil depth on MOAC and POC:


# MOAC 

by(CarbonData$MAOC, CarbonData$Grazing.mgt, stat.desc)

# The mean MAOC values under Controlled grazing management (0.361) are slightly higher than under Continuous grazing management (0.352), with lower variability observed in the controlled system. This suggests that controlled grazing practices may promote better vegetation recovery and organic matter accumulation, as rotational grazing allows for more rest periods for the soil and plants. This can enhance soil carbon sequestration by increasing plant biomass and organic inputs into the soil. In contrast, continuous grazing may lead to overgrazing, which reduces plant cover, limits carbon inputs, and results in greater variability in soil organic carbon levels due to uneven grazing pressure and soil degradation.

by(CarbonData$MAOC, CarbonData$Slope.position, stat.desc)

# The analysis of Mineral-Associated Organic Carbon (MAOC) reveals that the mean is highest in Bottom Land (0.367), followed by Mid Slope (0.358) and Footslope (0.344), with Mid Slope exhibiting the most variability. The elevated mean in Bottom Land can be attributed to reduced erosion, improved water retention, and the accumulation of organic matter in lower slope positions, all of which enhance carbon storage. Mid Slope likely retains moderate organic carbon but faces greater erosion, contributing to its higher variability in MAOC values. The lower mean in Footslope may stem from more frequent soil disturbances and reduced organic matter deposition compared to Bottom Land, although it still benefits from some runoff accumulation. Overall, these findings underscore how slope position significantly influences organic carbon dynamics, with flatter areas favoring the retention of carbon-rich materials.

by(CarbonData$MAOC, CarbonData$Land.cover.type, stat.desc)

# The mean MAOC is highest in Bare land (0.417), followed by Tree cover (0.331) and Grass cover (0.326). In bare land, the higher MAOC may be attributed to the direct accumulation of organic matter from various sources, including dust deposition and organic residues that are not masked by vegetation. The absence of plant cover allows for less competition for nutrients and promotes the accumulation of carbon-rich materials. In contrast, tree cover, while beneficial for carbon sequestration, can lead to lower MAOC due to the shading effect, which reduces the decomposition rates of organic matter on the soil surface. Trees also have deeper root systems that may access different soil layers, potentially leading to a redistribution of organic carbon rather than a concentration in the topsoil. Grass cover, although it contributes to organic carbon through root biomass and litter, often experiences more frequent disturbances from grazing or mowing, which can further reduce the accumulation of MAOC. Additionally, the shorter lifespan and lower biomass of grass compared to trees may result in less organic matter being deposited in the soil.


# The higher MAOC in bare land could be due to minimal plant uptake and decomposition of organic material left undisturbed, allowing more organic matter to accumulate in the soil. In Tree cover, organic carbon inputs from leaf litter and root turnover are more consistent, but decomposition rates may balance this input. Grass cover shows the lowest MAOC, possibly due to faster decomposition and lower organic carbon inputs compared to tree cover, as well as differences in root biomass.

by(CarbonData$MAOC, CarbonData$Soil.depth, stat.desc)

# The mean MAOC is highest at the 20 cm soil depth (0.390), followed by 10 cm (0.342) and 30 cm (0.338). The increased MAOC at 20 cm may be due to a balance between organic matter inputs from root biomass and reduced microbial decomposition at deeper levels, where moisture retention and lower oxygen levels slow the breakdown of organic material. At 10 cm, while organic inputs are higher from surface vegetation, more rapid decomposition could lower MAOC. The 30 cm depth shows the lowest mean, likely due to reduced organic inputs as roots and organic matter decrease with depth.


# POC

by(CarbonData$POC, CarbonData$Grazing.mgt, stat.desc)

# The mean POC (particulate organic carbon) is higher under controlled grazing (0.683) compared to continuous grazing (0.548), with controlled grazing also exhibiting greater variability (standard deviation of 0.426 compared to 0.272). The higher POC in controlled grazing likely results from better management of vegetation and soil compaction, allowing organic matter to accumulate and decompose more slowly, preserving carbon. Continuous grazing, with more intensive livestock impact, likely leads to greater soil disturbance, reducing carbon sequestration and increasing decomposition rates.

by(CarbonData$POC, CarbonData$Slope.position, stat.desc)

# The mean POC is highest in bottom land (0.754), followed by footslope (0.640), and lowest in mid slope (0.454). Bottom land shows greater POC accumulation, likely due to increased deposition of organic matter from higher slope positions, more stable moisture retention, and reduced erosion. In contrast, mid slopes tend to experience greater erosion and runoff, leading to lower organic carbon retention. Footslope areas, being intermediate, receive some deposition but also experience more erosion than bottom lands, explaining the moderate POC values.

by(CarbonData$POC, CarbonData$Land.cover.type, stat.desc)

# The distribution of particulate organic carbon (POC) across different land cover types shows that tree-covered areas have the highest mean POC (0.891), with a wide range (0.440 to 1.520), likely due to high organic matter inputs from tree litter, root biomass, and reduced erosion. Grass-covered areas follow with a mean POC of 0.666 and a similarly wide range (0.110 to 1.430), as grasslands accumulate carbon through root turnover and ground cover, though they exhibit more variability. Bare land has the lowest mean POC (0.291), reflecting minimal organic input and higher erosion susceptibility, which reduces carbon retention. This variability in POC is primarily driven by differences in organic inputs, soil protection from erosion, and vegetation's role in soil structure and microbial activity.

by(CarbonData$POC, CarbonData$Soil.depth, stat.desc)

# Particulate organic carbon (POC) levels show that soil depth influences carbon content, with the deepest soils (30 cm) having the lowest mean POC (0.414) and highest variability (range of 0.090 to 0.940), likely due to reduced organic matter input and higher decomposition rates at greater depths. Intermediate depths (20 cm) exhibit a mean POC of 0.631, indicating moderate carbon storage, while the shallowest soils (10 cm) have the highest mean POC (0.802) and variability (range of 0.160 to 1.520), reflecting higher organic matter inputs and less decomposition. This trend suggests that shallower soils may retain more organic carbon due to higher surface vegetation and reduced decomposition, while deeper soils might lose carbon more rapidly through leaching and microbial activity.


# Descriptive statistics for all combinations of levels of the variables 

# Combined descriptive statistics for MAOC
by(CarbonData$MAOC, list(CarbonData$Grazing.mgt, CarbonData$Slope.position, CarbonData$Land.cover.type, CarbonData$Soil.depth), stat.desc, basic = FALSE)


# The analysis of mean active organic carbon (MAOC) reveals that the highest mean values are associated with Controlled grazing practices, particularly in the Mid slope with Bare land, which recorded a mean of 0.4867. This is followed by Footslope with Bare land at 0.4433 and Bottom land with Bare land at 0.3967. In contrast, the lowest mean MAOC values were observed in Continuous grazing, specifically in the Mid slope with Tree cover, showing a mean of 0.2000, followed by Footslope with Grass at 0.2533 and Bottom land with Grass at 0.2967. These findings underscore the significant impact of grazing management and land cover type on carbon storage in these ecosystems.


# Combined descriptive statistics for POC
by(CarbonData$POC, list(CarbonData$Grazing.mgt, CarbonData$Slope.position, CarbonData$Land.cover.type, CarbonData$Soil.depth), stat.desc, basic = FALSE)


# The analysis of particulate organic carbon (POC) shows that the highest mean values are associated with Controlled grazing practices, particularly in the Bottom land with Tree cover, which recorded a mean of 1.4933. This is followed by Bottom land with Grass at 1.3900 and Footslope with Tree cover at 1.3533. In contrast, the lowest mean POC values were observed in the Additional Combinations at a soil depth of 30, with Mid slope Bare land showing a mean of 0.1033, Footslope Bare land at 0.1767, and Bottom land Bare land at 0.1867. These findings highlight the significant impact of grazing management and land cover type on carbon storage in these ecosystems.



# Graphs

# Boxplots

boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC))
boxplot + geom_boxplot() + facet_wrap(~Slope.position) + labs(x = "Grazing Management", y = "MAOC")

# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Slope.position) + 
    labs(title = "Effect of Grazing Management on MAOC Across slope Positions", 
         x = "Grazing Management", 
         y = "MAOC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold")))


# Bolding axes

(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Slope.position) + 
    labs(title = "Effect of Grazing Management on MAOC Across Slope Positions", 
         x = "Grazing Management", 
         y = "MAOC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 


# The box plot demonstrates that Continuous grazing management leads to higher MAOC levels only in the Bottom land position. In both the Footslope and Mid slope positions, Controlled grazing shows higher MAOC values. 

boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC))
boxplot + geom_boxplot() + facet_wrap(~Land.cover.type) + labs(x = "Grazing Management", y = "MAOC")


# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Land.cover.type) + 
    labs(title = "Effect of Grazing Management on MAOC Across Land Cover Types", 
         x = "Grazing Management", 
         y = "MAOC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 




boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC))
boxplot + geom_boxplot() + facet_wrap(~Soil.depth) + labs(x = "Grazing Management", y = "MAOC")


# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, MAOC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Soil.depth) + 
    labs(title = "Effect of Grazing Management on MAOC Across Soil Depths", 
         x = "Grazing Management", 
         y = "MAOC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 






boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC))
boxplot + geom_boxplot() + facet_wrap(~Slope.position) + labs(x = "Grazing Management", y = "POC")

# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Slope.position) + 
    labs(title = "Effect of Grazing Management on POC Across Slope Positions", 
         x = "Grazing Management", 
         y = "POC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 



boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC))
boxplot + geom_boxplot() + facet_wrap(~Land.cover.type) + labs(x = "Grazing Management", y = "POC")

# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Land.cover.type) + 
    labs(title = "Effect of Grazing Management on POC in Land Cover Types", 
         x = "Grazing Management", 
         y = "POC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 




boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC))
boxplot + geom_boxplot() + facet_wrap(~Soil.depth) + labs(x = "Grazing Management", y = "POC")

# Or
(boxplot <- ggplot(CarbonData, aes(Grazing.mgt, POC)) +
    geom_boxplot(aes(fill = Grazing.mgt), show.legend = FALSE) +  
    facet_wrap(~Soil.depth) + 
    labs(title = "Effect of Grazing Management on POC Across Soil Depths", 
         x = "Grazing Management", 
         y = "POC (%)") +
    scale_fill_manual(values = c("orange", "lightgreen")) +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title = element_text(face = "bold"))) 




# Interaction plot

# Note what increases as you move from whwt to what.

# MAOC
(line <- ggplot(CarbonData, aes(Grazing.mgt, MAOC, colour = Land.cover.type)) +
  stat_summary(fun = mean, geom = "point") +
  stat_summary(fun = mean, geom = "line", aes(group = Land.cover.type), size = 1.2) +  # Bold lines
  stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width = 0.2, size = 1.2) +  # Bold error bars
  labs(x = "Grazing Management", y = "Mean MAOC (%)", colour = "Land.cover.type") +
  ggtitle("Grazing-Land Cover Interaction for MAOC") +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        axis.title = element_text(face = "bold")))  # Bold axes titles





# Under Controlled Grazing, Grass can sequester more carbon than Tree cover, while under Continuous Grazing, Tree cover may perform better than Grass.


# POC
(line <- ggplot(CarbonData, aes(Grazing.mgt, POC, colour = Land.cover.type)) +
  stat_summary(fun = mean, geom = "point") +
  stat_summary(fun = mean, geom = "line", aes(group = Land.cover.type), size = 1.2) +  # Bold lines
  stat_summary(fun.data = mean_cl_boot, geom = "errorbar", width = 0.2, size = 1.2) +  # Bold error bars
  labs(x = "Grazing Management", y = "Mean POC (%)", colour = "Land.cover.type") +
  ggtitle("Grazing-Land Cover Interaction for POC") +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        axis.title = element_text(face = "bold")))  # Bold axes titles



# Bar plots

# MAOC

# By Grazing mgt levels
bar <- ggplot(CarbonData, aes(Grazing.mgt, MAOC, fill = Land.cover.type))
bar + stat_summary(fun = mean, geom = "bar", position="dodge") + stat_summary(fun.data = mean_cl_normal, geom = "errorbar", position=position_dodge(width=0.90), width = 0.2) + labs(x = "Grazing Management", y = "Mean MAOC", fill = "Land.cover.type")


# By Land cover type
bar <- ggplot(CarbonData, aes(Land.cover.type, MAOC))
bar + stat_summary(fun = mean, geom = "bar", fill = "White", colour = "Black") + stat_summary(fun.data = mean_cl_normal, geom = "pointrange") + labs(x = "Land.cover.type", y = "Mean MAOC") + scale_y_continuous(breaks=seq(0,80, by = 10))



# POC

# By Grazing mgt levels
bar <- ggplot(CarbonData, aes(Grazing.mgt, POC, fill = Land.cover.type))
bar + stat_summary(fun = mean, geom = "bar", position="dodge") + stat_summary(fun.data = mean_cl_normal, geom = "errorbar", position=position_dodge(width=0.90), width = 0.2) + labs(x = "Grazing Management", y = "Mean MAOC", fill = "Land.cover.type")


# By Land cover type
bar <- ggplot(CarbonData, aes(Land.cover.type, POC))
bar + stat_summary(fun = mean, geom = "bar", fill = "White", colour = "Black") + stat_summary(fun.data = mean_cl_normal, geom = "pointrange") + labs(x = "Land.cover.type", y = "Mean POC") + scale_y_continuous(breaks=seq(0,80, by = 10))


# By Grazing mgt irrespective of Land cove type
bar <- ggplot(CarbonData, aes(Grazing.mgt, MAOC))
bar + stat_summary(fun = mean, geom = "bar", fill = "White", colour = "Black") + stat_summary(fun.data = mean_cl_normal, geom = "pointrange") + labs(x = "Grazing Management", y = "Mean MAOC") + scale_y_continuous(breaks=seq(0,80, by = 10))


bar <- ggplot(CarbonData, aes(Grazing.mgt, POC))
bar + stat_summary(fun = mean, geom = "bar", fill = "White", colour = "Black") + stat_summary(fun.data = mean_cl_normal, geom = "pointrange") + labs(x = "Grazing Management", y = "Mean POC") + scale_y_continuous(breaks=seq(0,80, by = 10))



# Levene's Test

# Does the variance in attractiveness differ across different Grazing mgt and land cover types seperately?

leveneTest(CarbonData$MAOC, CarbonData$Grazing.mgt, center = median)
leveneTest(CarbonData$MAOC, CarbonData$Land.cover.type, center = median)
#### Explain above
  
# We're primarily interested in the interaction of these variables, so we would ideally like to know whether the variances differ across all groups. 
# To do this, we can add the interaction() option to the leveneTest() function, which will compute Levene's test across any combination of groups for the variables specified within interaction().

leveneTest(CarbonData$MAOC, interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type), center = median)

#### Explain


# POC

leveneTest(CarbonData$POC, CarbonData$Grazing.mgt, center = median)
leveneTest(CarbonData$POC, CarbonData$Land.cover.type, center = median)

leveneTest(CarbonData$POC, interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type), center = median)


# Shapiro-Wilk

# Shapiro-Wilk Test for MAOC by Grazing Management
(maoc_grazing <- tapply(CarbonData$MAOC, CarbonData$Grazing.mgt, shapiro.test))

# Shapiro-Wilk Test for MAOC by Land Cover Type
(maoc_landcover <- tapply(CarbonData$MAOC, CarbonData$Land.cover.type, shapiro.test))

# Shapiro-Wilk Test for MAOC by interaction of Grazing Management and Land Cover Type
(maoc_interaction <- tapply(CarbonData$MAOC, interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type), shapiro.test))

# Shapiro-Wilk Test for POC by Grazing Management
(poc_grazing <- tapply(CarbonData$POC, CarbonData$Grazing.mgt, shapiro.test))

# Shapiro-Wilk Test for POC by Land Cover Type
(poc_landcover <- tapply(CarbonData$POC, CarbonData$Land.cover.type, shapiro.test))

# Shapiro-Wilk Test for POC by interaction of Grazing Management and Land Cover Type
(poc_interaction <- tapply(CarbonData$POC, interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type), shapiro.test))

# For MAOC, Levene's test showed that homogeneity of variance was not violated for grazing management, land cover type, or their interaction (p-values > 0.05). However, the Shapiro-Wilk test indicated that normality was violated for MAOC in most groups, particularly under the "Bare" and "Tree" land cover types and the "Continuous" grazing management.

# For POC, Levene's test showed significant differences in variance across grazing management, land cover type, and their interaction (p-values < 0.001). The Shapiro-Wilk test also indicated non-normality for POC in several groups, especially in "Continuous" grazing management under "Bare" and "Grass" land cover types.



# Melting

# Melt the data to long format
CarbonData_melted <- melt(CarbonData, id.vars = c("Grazing.mgt", "Slope.position", "Land.cover.type", "Soil.depth"), 
                  measure.vars = c("MAOC", "POC"),
                  variable.name = "Variable", value.name = "Value")


head(CarbonData_melted)



# Log transforming

# Convert the Value column to numeric
CarbonData_melted$value <- as.numeric(as.character(CarbonData_melted$value))

# Check for any NA values after conversion
sum(is.na(CarbonData_melted$value))  # This will show the count of NA values


# Log-transforming the 'value' column in CarbonData_melted

# Adding a small constant (e.g., 0.001) to avoid log(0) errors

CarbonData_melted$log_value <- log(CarbonData_melted$value + 0.001, base = 10)

# Removing rows with zero or negative values in the 'log_value' column (in case any issues remain)
CarbonData_melted <- CarbonData_melted[CarbonData_melted$log_value > 0, ]

head(CarbonData_melted)



# Levene's Test for Log-Transformed Data

# Levene's Test for log-transformed values based on grouping factors
# For Grazing management
leveneTest(log_value ~ Grazing.mgt, data = CarbonData_melted, center = median)

# For Land cover type
leveneTest(log_value ~ Land.cover.type, data = CarbonData_melted, center = median)

# For interaction of Grazing management and Land cover type
leveneTest(log_value ~ interaction(Grazing.mgt, Land.cover.type), data = CarbonData_melted, center = median)



# Shapiro-Wilk test for normality for each factor combination

# Normality of log-transformed values within each group

# By Grazing management
(shapiro_test_grazing <- tapply(CarbonData_melted$log_value, CarbonData_melted$Grazing.mgt, shapiro.test))


# By Land cover type
(shapiro_test_landcover <- tapply(CarbonData_melted$log_value, CarbonData_melted$Land.cover.type, shapiro.test))


# By interaction of Grazing management and Land cover type
shapiro_test_interaction <- tapply(CarbonData_melted$log_value, interaction(CarbonData_melted$Grazing.mgt, CarbonData_melted$Land.cover.type), shapiro.test)
shapiro_test_interaction

# Error due to 2 grazings



# Decision and Stats 

# Levene and shapiro fail even after log transformation. So we run the non parametric versions, and respective post hocs.

# Given the focus on the effects of grazing management and land cover types on mineral-associated organic carbon (MAOC) and particulate organic carbon (POC), while also considering soil depth as a continuous variable, the most appropriate choice would be: ANCOVA.


# If not interested in soil depth and want to focus solely on the effects of grazing management, land cover types, and slope position on MAOC and POC, then Factorial ANOVA would be the most appropriate choice.


# Kruskall - Not appropriate for the continous variables.


# Kruskal-Wallis Test for MAOC

# Kruskal-Wallis test for grazing management and MAOC
(kruskal_test_grazing_maoc <- kruskal.test(MAOC ~ Grazing.mgt, data = CarbonData))

# Kruskal-Wallis test for land cover type and MAOC
(kruskal_test_landcover_maoc <- kruskal.test(MAOC ~ Land.cover.type, data = CarbonData))

# Kruskal-Wallis test for slope position and MAOC
(kruskal_test_slope_maoc <- kruskal.test(MAOC ~ Slope.position, data = CarbonData))

# Interaction of Grazing management and land cover type with MAOC
(kruskal_test_interaction_maoc <- kruskal.test(MAOC ~ interaction(Grazing.mgt, Land.cover.type), data = CarbonData))


# Post hoc for MAOC

# Load the dunn.test library
if (!require("dunn.test")) install.packages("dunn.test")
library(dunn.test)

# Dunn's test for grazing management and MAOC
(dunn_grazing_maoc <- dunn.test(CarbonData$MAOC, CarbonData$Grazing.mgt, method = "bonferroni"))


# Dunn's test for land cover type and MAOC
(dunn_landcover_maoc <- dunn.test(CarbonData$MAOC, CarbonData$Land.cover.type, method = "bonferroni"))


# Dunn's test for slope position and MAOC
(dunn_slope_maoc <- dunn.test(CarbonData$MAOC, CarbonData$Slope.position, method = "bonferroni"))


# Dunn's test for interaction of Grazing mgt and Land cover type with MAOC

# Combine factors into a single factor
interaction_factor_maoc <- interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type)

dunn_interaction_maoc <- dunn.test(CarbonData$MAOC, interaction_factor_maoc, method = "bonferroni")
print(dunn_interaction_maoc)


# The Kruskal-Wallis test revealed no significant differences in Mineral-Associated Organic Carbon (MAOC) levels among different Grazing management types, with a chi-squared value of 0.6998 and a p-value of 0.4029.

# The Kruskal-Wallis test for MAOC across different land cover types reveals a significant difference (χ² = 42.701, df = 2, p-value < 0.001). This indicates that MAOC values differ significantly among land cover types. Subsequent Dunn's post-hoc test, adjusted for multiple comparisons, shows significant differences between the "Bare" and "Grass" land cover types (p < 0.001) and between the "Bare" and "Tree" land cover types (p < 0.001). However, there is no significant difference between "Grass" and "Tree" (p = 0.7277). These results suggest that MAOC levels are notably higher in "Bare" land cover compared to both "Grass" and "Tree" types, but there are no significant differences between "Grass" and "Tree" land cover types. This pattern may be attributed to differences in soil properties or vegetation cover that affect the retention and availability of mineral-associated organic carbon. ####### First, "Bare" land may have undergone disturbances that initially expose mineral soils, which can temporarily elevate MAOC levels due to increased mineralization and organic matter inputs from surrounding vegetation. Additionally, the lack of vegetation in "Bare" land may lead to less competition for nutrients, allowing for greater accumulation of organic carbon. Conversely, "Grass" and "Tree" land cover types typically support more stable ecosystems where organic carbon is sequestered in plant biomass and litter, resulting in lower MAOC values due to higher rates of organic matter stabilization. The similarity in MAOC between "Grass" and "Tree" could indicate that both types effectively retain carbon, but the specific soil properties, root structures, and microbial communities associated with these vegetative types may not significantly differ in their capacity to enhance MAOC levels. Overall, these dynamics highlight the complex interplay between land cover, soil properties, and carbon cycling processes.

# The Kruskal-Wallis test for MAOC across different slope positions shows no significant differences (χ² = 2.6906, df = 2, p = 0.2605). Footslope > Midslope > Bottomland.


# A Kruskal-Wallis rank sum test was conducted to evaluate the effect of the interaction between grazing management and land cover type on MAOC, revealing a statistically significant result (χ² = 48.498, df = 5, p < 0.001). Post-hoc Dunn’s test with Bonferroni correction identified several significant differences between grazing and land cover combinations. Notable significant pairwise comparisons included Continuous.Bare vs Continuous.Grass (Z = 5.73, p < 0.001), Continuous.Bare vs Continuous.Tree (Z = 4.01, p = 0.0005), Continuous.Bare vs Controlled.Bare (Z = 5.02, p < 0.001), Continuous.Bare vs Controlled.Tree (Z = 4.16, p < 0.001), Continuous.Grass vs Controlled.Bare (Z = 3.43, p = 0.0046), and Controlled.Bare vs Controlled.Tree (Z = 3.45, p = 0.0041). Additional significant comparisons were observed between Continuous .Grass vs Controlled.Tree (Z = 2.73, p = 0.048) and Controlled.Bare vs Controlled.Grass (Z = 2.73, p = 0.048).

  
# The significant results from the Kruskal-Wallis test, followed by Dunn's post-hoc test, suggest that grazing management and land cover type interact to influence the amount of mineral-associated organic carbon (MAOC). The strong differences observed between Continuous.Bare vs Continuous.Grass and Continuous.Bare vs Continuous.Tree indicate that bare land in continuous grazing systems may result in lower MAOC compared to vegetated areas, likely due to reduced organic inputs and increased soil erosion in bare land. Continuous.Bare vs Controlled.Bare being significant may highlight the positive effects of controlled grazing on soil carbon sequestration, as controlled grazing can enhance plant regrowth and root biomass, contributing to MAOC. Similarly, the significance of Continuous.Bare vs Controlled.Tree may reflect the positive impact of trees in managed systems, where tree cover enhances litterfall and root carbon inputs into the soil, improving MAOC.

# The additional significant differences, such as Continuous.Grass vs Controlled.Bare and Controlled.Bare vs Controlled.Tree, further reinforce the idea that controlled management, whether through reducing grazing intensity or integrating tree cover, promotes soil carbon accumulation. Grassland systems, particularly in controlled grazing scenarios, may provide more continuous organic matter inputs and protective soil cover, thus boosting carbon retention compared to overgrazed or bare lands. Controlled grazing practices can also reduce soil compaction and erosion, further improving carbon storage capacity.




# POC

# Kruskal-Wallis Test for POC

# Kruskal-Wallis test for grazing management and POC
(kruskal_test_grazing_poc <- kruskal.test(POC ~ Grazing.mgt, data = CarbonData))

# Kruskal-Wallis test for land cover type and POC
(kruskal_test_landcover_poc <- kruskal.test(POC ~ Land.cover.type, data = CarbonData))

# Kruskal-Wallis test for slope position and POC
(kruskal_test_slope_poc <- kruskal.test(POC ~ Slope.position, data = CarbonData))


# Interaction of Grazing management and Land cover type with POC
(kruskal_test_interaction_poc <- kruskal.test(POC ~ interaction(Grazing.mgt, Land.cover.type), data = CarbonData))



# POC post-hoc


# Load the dunn.test library
library(dunn.test)

# Dunn's test for grazing management and POC
(dunn_grazing_poc <- dunn.test(CarbonData$POC, CarbonData$Grazing.mgt, method = "bonferroni"))

# Dunn's test for land cover type and POC
(dunn_landcover_poc <- dunn.test(CarbonData$POC, CarbonData$Land.cover.type, method = "bonferroni"))

# Dunn's test for slope position and POC
(dunn_slope_poc <- dunn.test(CarbonData$POC, CarbonData$Slope, method = "bonferroni"))



# Dunn's test for interaction of grazing mgt and land cover type with POC

# Combine factors into a single factor
interaction_factor_poc <- interaction(CarbonData$Grazing.mgt, CarbonData$Land.cover.type)

dunn_interaction_poc <- dunn.test(CarbonData$POC, interaction_factor_poc, method = "bonferroni")
print(dunn_interaction_poc)


# The result was not statistically significant (χ² = 3.06, df = 1, p = 0.080), indicating no strong evidence of a difference in POC between continuous and controlled grazing management systems. 

# The non-significant result suggests that grazing management may not have a strong or consistent impact on particulate organic carbon (POC) in the studied context. While the marginal significance in Dunn’s test hints at a possible difference between continuous and controlled grazing, it was not robust enough to conclusively reject the null hypothesis. This could indicate that other factors, such as soil type, vegetation, or time under management, may have a more significant influence on POC, or that the difference in grazing intensity was not substantial enough to result in clear changes in POC levels.


# A Kruskal-Wallis rank sum test was performed to examine the effect of land cover type on particulate organic carbon (POC), yielding a highly significant result (χ² = 83.53, df = 2, p < 0.001). This indicates that land cover type has a statistically significant effect on POC. Post-hoc Dunn's test with Bonferroni correction further identified significant pairwise differences between Bare vs Grass (Z = -5.89, p < 0.001), Bare vs Tree (Z = -9.00, p < 0.001), and Grass vs Tree (Z = -3.10, p = 0.0029).

# The significant differences observed in POC across land cover types suggest that vegetation plays a critical role in carbon dynamics. The lower POC levels in bare land compared to grassland and tree-covered areas are likely due to the lack of organic matter input from vegetation. Trees, having a more substantial and long-lasting biomass, likely contribute more to POC than grass, which may explain the significant difference between tree-covered and grassland areas. The results emphasize the importance of vegetation cover in maintaining and enhancing soil carbon stocks.

# NB: The Dunn's test results show that tree-covered areas had the highest particulate organic carbon (POC) levels, as indicated by the significant negative Z-scores when compared with both bare land (Z = -9.00) and grassland (Z = -3.10). Conversely, bare land had the lowest POC levels, as indicated by its significant differences with both grassland (Z = -5.89) and tree-covered areas (Z = -9.00). Therefore, the POC levels follow this order: Tree > Grass > Bare.

# The Kruskal-Wallis test for slope position and POC revealed a statistically significant result (χ² = 19.715, df = 2, p < 0.001). Post-hoc Dunn’s test with Bonferroni correction showed significant differences in POC levels between Bottom land and Mid slope (Z = 4.33, p < 0.001), and between Footslope and Mid slope (Z = 3.01, p = 0.0039). However, the difference between Bottom land and Footslope was not significant (Z = 1.32, p = 0.28).

# These results suggest that the Mid slope position has significantly higher POC compared to both Bottom land and Footslope. The non-significant difference between Bottom land and Footslope indicates that POC levels are more similar between these two positions. 

# The observed differences in Particulate Organic Carbon (POC) across slope positions are likely due to variations in soil processes influenced by topography. Mid slopes typically have higher POC due to better drainage, reduced erosion, and increased organic matter input from vegetation, which enhances organic matter turnover. In contrast, bottom lands, with their poor drainage and sediment accumulation, experience slower decomposition and reduced POC, while footslopes, being transitional zones, have intermediate POC levels due to moderate drainage and sediment accumulation. 


# The Kruskal-Wallis test for the interaction between grazing management and land cover type on Particulate Organic Carbon (POC) yielded a statistically significant result (χ² = 90.156, df = 5, p < 2.2e-16). Post-hoc Dunn’s test with Bonferroni correction revealed significant differences among several combinations. Specifically, significant pairwise comparisons were observed between Continuous.Bare vs Continuous.Grass (Z = -4.88, p < 0.001), Continuous.Bare vs Continuous.Tree (Z = -5.74, p < 0.001), Continuous.Bare vs Controlled.Bare (Z = -1.07, p = 1.00), Continuous.Bare vs Controlled.Grass (Z = -4.52, p < 0.001), Continuous.Bare vs Controlled.Tree (Z = -8.05, p < 0.001), Continuous.Grass vs Controlled.Bare (Z = 3.81, p = 0.001), and Continuous.Grass vs Controlled.Tree (Z = -3.17, p = 0.011). Additionally, Controlled.Bare vs Controlled.Grass (Z = -2.32, p = 0.015) and Controlled.Bare vs Controlled.Tree (Z = -6.99, p < 0.001) showed significant differences.

# The significant differences in POC among the various combinations of grazing management and land cover types suggest that both factors and their interaction have a profound impact on soil organic carbon levels. The consistently lower POC in Continuous.Bare compared to other treatments indicates that bare land cover, especially under continuous grazing management, leads to reduced organic matter accumulation. Conversely, Continuous.Tree and Controlled.Tree conditions generally exhibited higher POC levels, likely due to the enhanced organic matter input and reduced soil disturbance associated with tree cover and controlled grazing. These findings emphasize the role of land management practices and vegetation cover in influencing soil carbon dynamics and highlight the need for tailored land management strategies to optimize soil carbon sequestration.



# Factorial AOV - MAOC
carbonModel <- aov (MAOC ~ Grazing.mgt + Land.cover.type:Grazing.mgt + Land.cover.type, data = CarbonData)
summary(carbonModel)


postHocs <- glht(carbonModel, linfct = mcp(Grazing.mgt = "Tukey"))
summary(postHocs)
confint(postHocs)


postHocs <- glht(carbonModel, linfct = mcp(Land.cover.type = "Tukey"))
summary(postHocs)
confint(postHocs)

# So for MAOC, we do post hocs for land cover type.



# Factorial AOV - POC
carbonModel1 <- aov (POC ~ Grazing.mgt + Land.cover.type:Grazing.mgt + Land.cover.type, data = CarbonData)
summary(carbonModel)


postHocs <- glht(carbonModel1, linfct = mcp(Grazing.mgt = "Tukey"))
summary(postHocs)
confint(postHocs)


postHocs <- glht(carbonModel1, linfct = mcp(Land.cover.type = "Tukey"))
summary(postHocs)
confint(postHocs)





############ More exploration and graphics

#### Explorations for MAOC

# Installing and loading the necessary libraries

if(!require(multcomp))install.packages("multcomp")
if(!require(multcompView))install.packages("multcompView")
if(!require(flextable))install.packages("flextable")
if(!require(WRS2))install.packages("WRS2")
if(!require(fastDummies))install.packages("fastDummies")
if(!require(magrittr))install.packages("magrittr")
if(!require(dplyr))install.packages("dplyr")


# Ensure Grazing.mgt is a factor
CarbonData$Land.cover.type <- as.factor(CarbonData$Land.cover.type)

# Fit the model
carbonModel5 <- lm(MAOC ~ Land.cover.type, data = CarbonData)

# Post-Hoc Tukey Test
library(multcomp)  # Load the multcomp package
postHocs05 <- glht(carbonModel5, linfct = mcp(Land.cover.type = "Tukey"))

# Summary and confidence intervals
summary(postHocs05)
conf.postHocs5 <- confint(postHocs05)

# Adjust margins and plot
par(mar=c(5,10,5,2) + 0.1)  # Adjust margins as needed
plot(postHocs05, col = "red", cex = 1.5)




# If you prefer to use letter superscripts on the the means especially to tabulate the results in manuscripts:
CarbonModel <- aov(MAOC ~ Land.cover.type, data = CarbonData) #The ANOVA model

tukey.test <- TukeyHSD(CarbonModel)

comp.letters <- multcompLetters4(CarbonModel,tukey.test)

# Extracting the compact letter display and adding to the Tk table
comp.letters <- as.data.frame.list(comp.letters$Land.cover.type)

Grp.Comp <- group_by(CarbonData, Land.cover.type) %>%
  summarise(mean = mean(MAOC),std.dev = sd(MAOC), 
            quant = quantile(MAOC, probs = 0.75)) %>%
  arrange(desc(mean))

Grp.Comp$letters <- comp.letters$Letters

# Plot the tables with the letters
Grp.Comp



# Printing a publishable table with the letters
# In this section we shall use the functions in the rempsy and flextable to generate the table, and print a publishable table to a word document.
mean.sd <- paste(round(Grp.Comp$mean,2),"±",round(Grp.Comp$std.dev,2),Grp.Comp$letters, sep = " ")

mean.sd <- data.frame(Grp.Comp$Land.cover.type,mean.sd);colnames(mean.sd) <- c("Land Cover","Mean ± SD")

mean.sd


mean.sd <- rempsyc::nice_table(mean.sd,
                               title = "Mean MAOC by Land Cover Type")
flextable::save_as_docx(mean.sd,path = "mean.sd.docx")

# See above table in the directory.



# plotting

# Plotting a violin plot with boxplot and letter display
ggplot(CarbonData, aes(x = Land.cover.type, y = MAOC)) +
  geom_violin(trim = 0.0, fill = "lightblue") +  # Violin plot with light blue fill
  geom_boxplot(col = "darkblue", fill = "orange", width = 0.5, outlier.shape = NA) +  # Boxplot on top with color settings
  theme_light() +  # Light theme for the plot
  geom_text(data = Grp.Comp, aes(x = Land.cover.type, y = quant, label = letters), 
            size = 4, vjust = -1, hjust = -1) +  # Add compact letter display
  labs(title = "Violin with Box Plot and Compact Letter Display", 
       x = "Land Cover Type", y = "MAOC (%)") +  # Labels for axes and title
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),  # Bold title centered
    axis.text.x = element_text(face = "bold"),  # Bold X-axis text
    axis.text.y = element_text(face = "bold"),  # Bold Y-axis text
    axis.title = element_text(face = "bold")  # Bold axis titles
  )




###### Interaction MAOC

# Ensure Grazing.mgt and Land.cover.type are factors
CarbonData$Grazing.mgt <- as.factor(CarbonData$Grazing.mgt)
CarbonData$Land.cover.type <- as.factor(CarbonData$Land.cover.type)

# Fit the interaction model
carbonModel <- aov(MAOC ~ Grazing.mgt * Land.cover.type, data = CarbonData)

# Post-Hoc Tukey Test for Interaction
library(multcomp)  # Load the multcomp package
postHocs05 <- glht(carbonModel, linfct = mcp(Grazing.mgt = "Tukey"))

postHocs05 <- glht(carbonModel, linfct = mcp(Land.cover.type = "Tukey"))

# Summary and confidence intervals for the interaction model
summary(postHocs05)
conf.postHocs5 <- confint(postHocs05)

# Adjust margins and plot for the interaction
par(mar = c(5, 10, 5, 2) + 0.1)  # Adjust margins as needed
plot(postHocs05, col = "red", cex = 1.5)

# Compact letters for interaction
tukey.test <- TukeyHSD(carbonModel)
comp.letters <- multcompLetters4(carbonModel, tukey.test)

# Extracting the compact letter display and adding to the summary table
comp.letters <- as.data.frame.list(comp.letters$`Grazing.mgt:Land.cover.type`)

# Summary statistics for interaction
Grp.Comp <- CarbonData %>%
  group_by(Grazing.mgt, Land.cover.type) %>%
  summarise(mean = mean(MAOC), std.dev = sd(MAOC), 
            quant = quantile(MAOC, probs = 0.75), .groups = "drop") %>%
  arrange(desc(mean))

# Add letters to the summary table
Grp.Comp$letters <- comp.letters$Letters

# Print the summary table with compact letters
print(Grp.Comp)


# Printing a publishable table with the letters
mean.sd <- paste(round(Grp.Comp$mean, 2), "±", round(Grp.Comp$std.dev, 2), Grp.Comp$letters, sep = " ")

mean.sd <- data.frame(Grp.Comp$Grazing.mgt, Grp.Comp$Land.cover.type, mean.sd)
colnames(mean.sd) <- c("Grazing Management", "Land Cover Type", "Mean ± SD")

# Create and save the publishable table
mean.sd <- rempsyc::nice_table(mean.sd, title = "Mean MAOC by Grazing Management and Land Cover Type")
flextable::save_as_docx(mean.sd, path = "mean_sd_interaction.docx")

# See above table in the directory.



# Plotting a violin plot with boxplot and letter display for interaction
ggplot(CarbonData, aes(x = interaction(Grazing.mgt, Land.cover.type), y = MAOC)) +
  geom_violin(trim = 0.0, fill = "lightblue") +  # Violin plot with light blue fill
  geom_boxplot(col = "darkblue", fill = "orange", width = 0.5, outlier.shape = NA) +  # Boxplot on top with color settings
  theme_light() +  # Light theme for the plot
  geom_text(data = Grp.Comp, aes(x = interaction(Grazing.mgt, Land.cover.type), y = quant, label = letters), 
            size = 4, vjust = -1, hjust = -1) +  # Add compact letter display
  labs(title = "Violin with Box Plot and Compact Letter Display", 
       x = "Grazing Management and Land Cover Type", y = "MAOC (%)") +  # Labels for axes and title
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),  # Bold title centered
    axis.text.x = element_text(face = "bold"),  # Bold X-axis text
    axis.text.y = element_text(face = "bold"),  # Bold Y-axis text
    axis.title = element_text(face = "bold")  # Bold axis titles
  )






#### Explorations for POC

# Installing and loading the necessary libraries

if(!require(multcomp))install.packages("multcomp")
if(!require(multcompView))install.packages("multcompView")
if(!require(flextable))install.packages("flextable")
if(!require(WRS2))install.packages("WRS2")
if(!require(fastDummies))install.packages("fastDummies")



# Ensure Grazing.mgt is a factor
CarbonData$Land.cover.type <- as.factor(CarbonData$Land.cover.type)

# Fit the model
carbonModel <- lm(POC ~ Land.cover.type, data = CarbonData)

# Post-Hoc Tukey Test
library(multcomp)  # Load the multcomp package
postHocs05 <- glht(carbonModel, linfct = mcp(Land.cover.type = "Tukey"))

# Summary and confidence intervals
summary(postHocs05)
conf.postHocs5 <- confint(postHocs05)

# Adjust margins and plot
par(mar=c(5,10,5,2) + 0.1)  # Adjust margins as needed
plot(postHocs05, col = "red", cex = 1.5)




# If you prefer to use letter superscripts on the the means especially to tabulate the results in manuscripts:
CarbonModel <- aov(POC ~ Land.cover.type, data = CarbonData) #The ANOVA model

tukey.test <- TukeyHSD(CarbonModel)

comp.letters <- multcompLetters4(CarbonModel,tukey.test)

# Extracting the compact letter display and adding to the Tk table
comp.letters <- as.data.frame.list(comp.letters$Land.cover.type)

Grp.Comp <- group_by(CarbonData, Land.cover.type) %>%
  summarise(mean = mean(POC),std.dev = sd(POC), 
            quant = quantile(POC, probs = 0.75)) %>%
  arrange(desc(mean))

Grp.Comp$letters <- comp.letters$Letters

# Plot the tables with the letters
Grp.Comp



# Printing a publishable table with the letters
# In this section we shall use the functions in the rempsy and flextable to generate the table, and print a publishable table to a word document.
mean.sd <- paste(round(Grp.Comp$mean,2),"±",round(Grp.Comp$std.dev,2),Grp.Comp$letters, sep = " ")

mean.sd <- data.frame(Grp.Comp$Land.cover.type,mean.sd);colnames(mean.sd) <- c("Land Cover","Mean ± SD")

mean.sd


mean.sd <- rempsyc::nice_table(mean.sd,
                               title = "Mean MAOC by Land Cover Type")
flextable::save_as_docx(mean.sd,path = "mean.sd.docx")

# See above table in the directory.



# plotting

# Plotting a violin plot with boxplot and letter display
ggplot(CarbonData, aes(x = Land.cover.type, y = POC)) +
  geom_violin(trim = 0.0, fill = "lightblue") +  # Violin plot with light blue fill
  geom_boxplot(col = "darkblue", fill = "orange", width = 0.5, outlier.shape = NA) +  # Boxplot on top with color settings
  theme_light() +  # Light theme for the plot
  geom_text(data = Grp.Comp, aes(x = Land.cover.type, y = quant, label = letters), 
            size = 4, vjust = -1, hjust = -1) +  # Add compact letter display
  labs(title = "Violin with Box Plot and Compact Letter Display", 
       x = "Land Cover Type", y = "POC (%)") +  # Labels for axes and title
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),  # Bold title centered
    axis.text.x = element_text(face = "bold"),  # Bold X-axis text
    axis.text.y = element_text(face = "bold"),  # Bold Y-axis text
    axis.title = element_text(face = "bold")  # Bold axis titles
  )




###### Interaction POC

# Ensure Grazing.mgt and Land.cover.type are factors
CarbonData$Grazing.mgt <- as.factor(CarbonData$Grazing.mgt)
CarbonData$Land.cover.type <- as.factor(CarbonData$Land.cover.type)

# Fit the interaction model
pocModel <- aov(POC ~ Grazing.mgt * Land.cover.type, data = CarbonData)

# Post-Hoc Tukey Test for Interaction
library(multcomp)  # Load the multcomp package
postHocsPocGrazing <- glht(pocModel, linfct = mcp(Grazing.mgt = "Tukey"))
postHocsPocLandCover <- glht(pocModel, linfct = mcp(Land.cover.type = "Tukey"))

# Summary and confidence intervals for the interaction model
summary(postHocsPocGrazing)
conf.postHocsPocGrazing <- confint(postHocsPocGrazing)

summary(postHocsPocLandCover)
conf.postHocsPocLandCover <- confint(postHocsPocLandCover)

# Adjust margins and plot for Grazing Management interaction

# Remove the hash, correct and run the following 4 lines of code
#par(mar = c(5, 10, 5, 2) + 0.1)  # Adjust margins as needed
#plot(postHocsPocGrazing, col = "red", cex = 1.5, main = "Post-Hoc Tukey for Grazing Management Interaction")

# Adjust margins and plot for Land Cover Type interaction
#par(mar = c(5, 10, 5, 2) + 0.1)  # Adjust margins as needed
# plot(postHocsPocLandCover, col = "blue", cex = 1.5, main = "Post-Hoc Tukey for Land Cover Type Interaction")

# Compact letters for interaction
tukey.testPoc <- TukeyHSD(pocModel)
comp.lettersPoc <- multcompLetters4(pocModel, tukey.testPoc)

# Extracting the compact letter display and adding to the summary table
comp.lettersPoc <- as.data.frame.list(comp.lettersPoc$`Grazing.mgt:Land.cover.type`)

# Summary statistics for interaction
Grp.CompPoc <- CarbonData %>%
  group_by(Grazing.mgt, Land.cover.type) %>%
  summarise(mean = mean(POC), std.dev = sd(POC), 
            quant = quantile(POC, probs = 0.75), .groups = "drop") %>%
  arrange(desc(mean))

# Add letters to the summary table
Grp.CompPoc$letters <- comp.lettersPoc$Letters

# Print the summary table with compact letters for POC
print(Grp.CompPoc)


# Printing a publishable table with the letters
mean.sd <- paste(round(Grp.CompPoc$mean, 2), "±", round(Grp.CompPoc$std.dev, 2), Grp.CompPoc$letters, sep = " ")

# Create a data frame for the publishable table
mean.sd.df <- data.frame(Grazing.Management = Grp.CompPoc$Grazing.mgt, 
                         Land.Cover.Type = Grp.CompPoc$Land.cover.type, 
                         `Mean ± SD` = mean.sd)

# Create and save the publishable table
mean.sd.table <- rempsyc::nice_table(mean.sd.df, title = "Mean POC by Grazing Management and Land Cover Type")
flextable::save_as_docx(mean.sd.table, path = "mean_sd_interaction_poc.docx")

# Check if the table is saved in the directory





# Plotting a violin plot with boxplot and letter display for interaction
ggplot(CarbonData, aes(x = interaction(Grazing.mgt, Land.cover.type), y = POC)) +
  geom_violin(trim = 0.0, fill = "lightblue") +  # Violin plot with light green fill
  geom_boxplot(col = "darkblue", fill = "orange", width = 0.5, outlier.shape = NA) +  # Boxplot on top with color settings
  theme_light() +  # Light theme for the plot
  geom_text(data = Grp.CompPoc, aes(x = interaction(Grazing.mgt, Land.cover.type), y = quant, label = letters), 
            size = 4, vjust = -1, hjust = -1) +  # Add compact letter display
  labs(title = "Violin with Box Plot and Compact Letter Display for POC", 
       x = "Grazing Management and Land Cover Type", y = "POC (%)") +  # Labels for axes and title
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5),  # Bold title centered
    axis.text.x = element_text(face = "bold"),  # Bold X-axis text
    axis.text.y = element_text(face = "bold"),  # Bold Y-axis text
    axis.title = element_text(face = "bold")  # Bold axis titles
  )





####### Visualizing in shiny

if(!require(shiny))install.packages("shiny") 
if(!require(bslib))install.packages("bslib") # For Bootstrap themes for Shiny apps, allowing for easy customization of UI.
if(!require(ggExtra))install.packages("ggExtra") # Enhances ggplot2 visualizations by adding marginal plots and other features.

library(shiny)
library(bslib)
library(dplyr)
library(ggplot2)
library(ggExtra)

# Load your carbon data
CarbonData <- read.csv("CarbonData.csv")

# Find subset of columns that are suitable for scatter plot
df_num <- CarbonData |> select(where(is.numeric))  # Select numeric columns

ui <- page_sidebar(
  sidebar = sidebar(
    varSelectInput("xvar", "X variable", df_num, selected = "MAOC"),  # Choose MAOC as default
    varSelectInput("yvar", "Y variable", df_num, selected = "POC"),   # Choose POC as default
    checkboxGroupInput(
      "land_cover", "Filter by land cover type",
      choices = unique(CarbonData$Land.cover.type),  # Choices based on your data
      selected = unique(CarbonData$Land.cover.type)
    ),
    hr(),
    checkboxInput("by_grazing", "Show grazing management", TRUE),
    checkboxInput("show_margins", "Show marginal plots", TRUE),
    checkboxInput("smooth", "Add smoother"),
  ),
  plotOutput("scatter")
)

server <- function(input, output, session) {
  subsetted <- reactive({
    req(input$land_cover)
    CarbonData |> filter(Land.cover.type %in% input$land_cover)  # Filter by selected land cover types
  })
  
  output$scatter <- renderPlot({
    p <- ggplot(subsetted(), aes(!!input$xvar, !!input$yvar)) + list(
      theme(legend.position = "bottom"),
      if (input$by_grazing) aes(color = Grazing.mgt),  # Color by grazing management
      geom_point(),
      if (input$smooth) geom_smooth()
    )
    
    if (input$show_margins) {
      margin_type <- if (input$by_grazing) "density" else "histogram"
      p <- ggExtra::ggMarginal(p, type = margin_type, margins = "both",
                               size = 8, groupColour = input$by_grazing, groupFill = input$by_grazing)
    }
    
    p
  }, res = 100)
}

shinyApp(ui, server)


