Data exploration season 1 trials

starting with soybean data season 1: I will explore differences in grain and biomass yields acrross treatments. the sample size is 20 farmers. each farmer represents a replicate in the experiment. Three (3) main treatments were:

  • Tripple Superphosephate (TSP) fertilizers
  • Rhizobioum inocualition
  • combination of rhizobium inoculation and TSP fertiliser

the first chunk of codes below loads the needed packages for my data analysis:

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(reshape2)
## 
## Attaching package: 'reshape2'
## 
## The following object is masked from 'package:tidyr':
## 
##     smiths
library(ggpubr)
## importing datafile of soybean experiment
ipungatrial <- read_csv("SOYA2true.csv")
## Rows: 20 Columns: 69
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (4): farmer_ID, farmer_name, village, crop
## dbl (49): freshweight_grainCONTROL, freshweight_grainTSP, freshweight_grainI...
## lgl (16): planting_datecroptype1, moisture_content%, nodulation, plant_pop, ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
ipungatrial2 <- read_csv("soyaN.csv")
## Rows: 12 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): farmerID, treatment
## dbl (4): Grain_N, Biomas_N, grainyield, biomassyield
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## melting dataframe above to allow for creating a boxplot
ipunga <- melt(ipungatrial, id.vars='farmer_ID', measure.vars=c('controlGRAIN_t.ha', 'tspGRAIN_t.ha', 'inocuGRAIN_t.ha', 'tsp_inocuGRAIN_t.ha'))
#melting ipungatrial df for creating biomas yield boxplot
ipunga3 <- melt(ipungatrial, id.vars='farmer_ID', measure.vars=c('controlBIO_t.ha', 'tspBIO_t.ha', 'inocuBIO_t.ha', 'tspinocuBIO_t.ha'))
colnames(ipunga3) <- c("farmer_ID", "treatment", "yieldbiomas")

ipungaN <- melt(ipungatrial, id.vars='farmer_ID', measure.vars=c('controlgrainN_kg.ha', 'tspgrainN_kg.ha', 'inocugrainN_kg.ha', 'tsp_inocugrainN_kg.ha'))
colnames(ipungaN) <- c("farmer_ID", "treatment2", "grain_N")
ipungaNreduced <- ipungaN %>% select(farmer_ID, grain_N)
#print(ipungaN)

ipungaNB <- melt(ipungatrial, id.vars='farmer_ID', measure.vars=c('controlBIO_Nkg.ha', 'tspBIO_Nkg.ha', 'inocuBIO_Nkg.ha', 'tspinocuBIO_Nkg.ha'))
colnames(ipungaNB) <- c("farmer_ID", "treatment", "Biomas_N")

#joining df 
ipungaYT <- full_join(ipunga, ipungaNreduced, by = "farmer_ID") # Apply full_join dplyr function
## Warning in full_join(ipunga, ipungaNreduced, by = "farmer_ID"): Detected an unexpected many-to-many relationship between `x` and `y`.
## ℹ Row 1 of `x` matches multiple rows in `y`.
## ℹ Row 1 of `y` matches multiple rows in `x`.
## ℹ If a many-to-many relationship is expected, set `relationship =
##   "many-to-many"` to silence this warning.
#print(ipungaYT)
#altenative melting several columns and renaming all at once
##ipunga3 <- melt(ipungatrial, id.vars= 'farmer_ID', measure.vars= list(c('controlGRAIN_t.ha', 'tspGRAIN_t.ha', 'inocuGRAIN_t.ha', 'tsp_inocuGRAIN_t.ha'), c('controlBIO_t.ha', 'tspBIO_t.ha', 'inocuBIO_t.ha', 'tspinocuBIO_t.ha')), + value.name = c('yieldgrain', 'yieldbiomas'))
 # Relevel factor labels in ipunga dataframe
ipunga2 <- ipunga
  levels(ipunga2$variable) <- c("Control", 
   "TSP fertiliser", "Inoculation", "TSP with Inoculation")
  
ipunga_df <- ipunga2[complete.cases(ipunga2),] # Remove incomplete rows 

#rename variables in ipunga_df
ipunga_df <- as_tibble(ipunga_df)
ipunga_df <- rename(ipunga_df, treatment = variable, g_yield = value)
#boxplot 1: grainyield
plot1 <- ggplot(ipunga_df, aes(x =treatment, y = g_yield, fill = treatment)) +
  geom_boxplot(width = 0.5, outlier.size = 1.4) + 
    stat_summary(fun = "mean", geom = "point",
               shape = 8,
               size = 3,
               color = "white")+
  labs(x="treatments", y= "grain yield (t/ha)",
       title="Soybean grain yields accross treatments",
         subtitle = "(n=20)")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.2), angle = 90, face = "bold")) +
  theme(axis.title.x = element_text(size = rel(1.2), angle = 360, face ="bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 12, 
    angle = 360,color ="black", face = "bold")) +
  theme(axis.text.y = element_text(size = 12,
    color ="black",face ="bold")) +
  theme(panel.background = element_blank())+
  theme(legend.position = "none")
#boxplot 2: biomas yield
plot2 <- ggplot(ipunga3, aes(x =treatment, y = yieldbiomas, fill = treatment)) +
  geom_boxplot(width = 0.5, outlier.size = 1.4) + 
    stat_summary(fun = "mean", geom = "point",
               shape = 8,
               size = 3,
               color = "white")+
  labs(x="treatments", y= "biomass yield (t/ha)",
       title="Soybean biomass yields accross treatments",
         subtitle = "(n=20)")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.2), angle = 90, face = "bold")) +
  theme(axis.title.x = element_text(size = rel(1.2), angle = 360, face ="bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 12, 
    angle = 360,color ="black", face = "bold")) +
  theme(axis.text.y = element_text(size = 12,
    color ="black",face ="bold")) +
  theme(panel.background = element_blank())+
  theme(legend.position = "none")
ggarrange(plot1 + rremove("x.text"), plot2, 
          labels = c("A", "B"),
          nrow = 2)
## Warning: Removed 4 rows containing non-finite values (`stat_boxplot()`).
## Warning: Removed 4 rows containing non-finite values (`stat_summary()`).

#geeom_point
ggplot(ipungatrial, aes(x = farmer_ID, y = controlGRAIN_t.ha, color = farmer_ID)) +
  geom_point()+ 
  ylab("maize yield (t/ha)") +
  xlab(" mineral N applied (kg N/ha) ")+
  ggtitle("scatter plot of maize yield against fertiliser N \non different field landscapes, n=360")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.0), angle = 90)) +
  theme(axis.title.x = element_text(size = rel(1.0), angle = 360)) +
  theme(legend.text = element_text(size = 11, colour = "black")) +
  theme(legend.title = element_text(size = 12, face = "bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 11, angle = 360)) +
  theme(axis.text.y = element_text(size = 11)) +
  theme(legend.position = "none")+
  theme(panel.background = element_blank())
## Warning: Removed 1 rows containing missing values (`geom_point()`).

#general
#geeom_point
ggplot(ipunga, aes(x = farmer_ID, y = value, color = variable)) +
  geom_point()+ 
  ylab("maize yield (t/ha)") +
  xlab(" mineral N applied (kg N/ha) ")+
  ggtitle("scatter plot of maize yield against fertiliser N \non different field landscapes, n=360")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.0), angle = 90)) +
  theme(axis.title.x = element_text(size = rel(1.0), angle = 360)) +
  theme(legend.text = element_text(size = 11, colour = "black")) +
  theme(legend.title = element_text(size = 12, face = "bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 11, angle = 360)) +
  theme(axis.text.y = element_text(size = 11)) +
  theme(legend.position = "bottom")+
  theme(panel.background = element_blank())
## Warning: Removed 4 rows containing missing values (`geom_point()`).

#arrange plots
#ggarrange(plota, plotb, plotc, plotd,
          #labels = c("A", "B","C", "D"),
#ggsave("plotG.png")
## summurize (means yields per treatment)
# Group by mean using dplyr
mean_yield <- ipunga_df %>% group_by(treatment) %>% 
  summarise(mean= mean(g_yield), std = sd(g_yield),
            .groups = 'drop') 
print(mean_yield)
## # A tibble: 4 × 3
##   treatment             mean   std
##   <fct>                <dbl> <dbl>
## 1 Control              0.939 0.566
## 2 TSP fertiliser       1.37  0.533
## 3 Inoculation          1.31  0.650
## 4 TSP with Inoculation 1.49  0.587
modelmean_yield <-lm(g_yield~treatment, data = ipunga_df)
summary(modelmean_yield)
## 
## Call:
## lm(formula = g_yield ~ treatment, data = ipunga_df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.91253 -0.44707 -0.09032  0.37393  1.40689 
## 
## Coefficients:
##                               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                     0.9393     0.1344   6.990 1.15e-09 ***
## treatmentTSP fertiliser         0.4342     0.1900   2.285  0.02527 *  
## treatmentInoculation            0.3728     0.1900   1.962  0.05366 .  
## treatmentTSP with Inoculation   0.5550     0.1900   2.921  0.00466 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.5857 on 72 degrees of freedom
## Multiple R-squared:  0.1167, Adjusted R-squared:  0.07991 
## F-statistic: 3.171 on 3 and 72 DF,  p-value: 0.02934
# plotting N and yields relationship
ggplot(ipungatrial2, aes(x=Grain_N, y=grainyield, colour = treatment )) +  
  geom_point(size = 3)+
  geom_smooth(data=subset(ipungatrial2, treatment == "control"),method='lm', aes(colour= treatment),size=1,se=FALSE)+
  geom_smooth(data=subset(ipungatrial2, treatment == "tsp"),method='lm', aes(colour= treatment),size=1,se=FALSE)+
  geom_smooth(data=subset(ipungatrial2, treatment == "inoculation"),method='lm', aes(colour= treatment),size=1,se=FALSE)+
  geom_smooth(data=subset(ipungatrial2, treatment == "tsp_inoc"),method='lm', aes(colour= treatment),size=1,se=FALSE)+
  labs(x="N uptake (kg/ha)", y= "maize yield (t/ha)",
       title=" Yield responses (t/ha) of soybeans \non different treatment", subtitle = "(n=3)")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.0), angle = 90)) +
  theme(axis.title.x = element_text(size = rel(1.0), angle = 360)) +
  theme(legend.text = element_text(size = 11, colour = "black")) +
  theme(legend.title = element_text(size = 12, face = "bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 11, angle = 360)) +
  theme(axis.text.y = element_text(size = 11)) +
  theme(legend.position = "bottom")+
  theme(panel.background = element_blank())
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using formula = 'y ~ x'

  #xlim(c(1, 100))+
  #ylim(c(1, 10))
 ggplot(ipungatrial2, aes(x =treatment, y = Grain_N, fill = treatment)) +
  geom_boxplot(width = 0.5, outlier.size = 1.4) + 
    stat_summary(fun = "mean", geom = "point",
               shape = 8,
               size = 3,
               color = "white")+
  labs(x="treatments", y= "N-uptake (kg/ha)",
       title="N uptake accross treatments",
         subtitle = "(n=20)")+
  theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.2), angle = 90, face = "bold")) +
  theme(axis.title.x = element_text(size = rel(1.2), angle = 360, face ="bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 12, 
    angle = 360,color ="black", face = "bold")) +
  theme(axis.text.y = element_text(size = 12,
    color ="black",face ="bold")) +
  theme(panel.background = element_blank())+
  theme(legend.position = "none")

 ggplot(mean_yield, aes(x=treatment, y=mean, fill=treatment))+
geom_bar(stat="identity", color="black")+
scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "red"))+
 theme(plot.title = element_text(size = rel(1.5), hjust = 0.5)) +
  theme(plot.subtitle = element_text(size = rel(1.0), hjust = 0.5)) +
  theme(axis.title.y = element_text(size = rel(1.0), angle = 90)) +
  theme(axis.title.x = element_text(size = rel(1.0), angle = 360)) +
  theme(legend.text = element_text(size = 11, colour = "black")) +
  theme(legend.title = element_text(size = 12, face = "bold")) +
  theme(panel.border = element_rect(linetype = "solid", fill = NA)) +
  theme(axis.text.x = element_text(size = 11, angle = 360)) +
  theme(axis.text.y = element_text(size = 12)) +
  theme(panel.background = element_blank())

#print(ipungatrial2)
df2 <- ipungatrial2 %>% 
  group_by(treatment) %>% 
  mutate(Grain_N = mean(Grain_N))
print(df2)
## # A tibble: 12 × 6
## # Groups:   treatment [4]
##    farmerID treatment   Grain_N Biomas_N grainyield biomassyield
##    <chr>    <chr>         <dbl>    <dbl>      <dbl>        <dbl>
##  1 f10      control        66.6     16.7      0.297         2.49
##  2 f10      tsp           118.      36.1      1.68          5.24
##  3 f10      inoculation   105.      36.8      2.17          3.12
##  4 f10      tsp_inoc       96.9     52.1      1.54          5.54
##  5 f11      control        66.6     19.1      1.47          2.52
##  6 f11      tsp           118.      53.8      2.28          5.18
##  7 f11      inoculation   105.      16.0      1.27          1.92
##  8 f11      tsp_inoc       96.9     29.6      1.93          4.63
##  9 f18      control        66.6     20.0      1.29          2.63
## 10 f18      tsp           118.      28.1      1.39          3.6 
## 11 f18      inoculation   105.      19.9      1.39          2.84
## 12 f18      tsp_inoc       96.9     34.6      1.01          4.50
# Assuming 'data' is your dataframe with columns: GrainYield, BiomassYield, NContent, Treatment
# 'Treatment' is a factor with levels: Control, TSP, Rhizobium, TSP_Inoculation

# Install and load the corrplot library if not already installed
#install.packages("corrplot")
library(corrplot)
## corrplot 0.92 loaded
# Subset the relevant columns
subset_data <- ipungatrial2[, c("grainyield", "biomassyield", "Grain_N", "treatment", "Biomas_N")]

# Convert 'Treatment' to a factor with appropriate levels
subset_data$treatment <- factor(subset_data$treatment, levels = c("control", "tsp", "inoculation", "tsp_inoc"))

# Calculate the correlation matrix
cor_matrix <- cor(subset_data[, c("grainyield", "biomassyield", "Grain_N", "Biomas_N")])
print(cor_matrix)
##              grainyield biomassyield   Grain_N  Biomas_N
## grainyield    1.0000000    0.4541737 0.9876737 0.6047616
## biomassyield  0.4541737    1.0000000 0.4465578 0.8726414
## Grain_N       0.9876737    0.4465578 1.0000000 0.5758160
## Biomas_N      0.6047616    0.8726414 0.5758160 1.0000000
# Create a correlation matrix heatmap
corrplot(cor_matrix, method = "color", type = "upper", addrect = 3)

# Adding color legend
legend("bottomleft", c("Pearson\nCorrelation"), col = c("white", "yellow", "orange", "red"), lty = 1, cex = 0.8)

# Install and load reshape2 package
install.packages("reshape2")
## Warning: package 'reshape2' is in use and will not be installed
library(reshape2)
 
# creating correlation matrix
corr_mat <- round(cor(cor_matrix),2)
 
# reduce the size of correlation matrix
melted_corr_mat <- melt(corr_mat)
# head(melted_corr_mat)
 
# plotting the correlation heatmap
library(ggplot2)
ggplot(data = melted_corr_mat, aes(x=Var1, y=Var2,
                                   fill=value)) + 
geom_tile()