---
title: "ANOVA and Multivariate Analysis"
output:
  html_document: default
  html_notebook: default
---

### Introduction
Many PhotosynQ users are interested in comparing the performance of different treatments, crop varieties, etc. A common approach to separate different groups is to use Analysis of Variance (ANOVA). However, many of the parameters measured by the MultispeQ device are affected by numerous factors including:

+ light intensity
+ time of measurement
+ temperature (the temperature data on the MultispeQ beta device was not accurate and can be ignored. However, if you are using the new MultispeQ v1.0, you should take temperature into account)
+ spatial location in the field, this is usually as a identified by ‘block’ or ‘replicate’
+ leaf age and position in the canopy
+ growth stage when data was collected
+ instrument/user variation. This could be caused user bias in selection of which leaf to measure or by device to device variation (especially in the MultispeQ Beta instruments, the new MultispeQ v1.0 instruments are much more consistent across instruments)
+ this is not an exhaustive list, but rather a summary of the most common factors affecting photosynthesis measurements.
In this tutorial, we will compare the performance of 4 varieties of sunflower. We will use the dataset ‘sun’ if you want to follow along with the tutorial.

In this example, four varieties of sunflower were planted in a complete block design with 4 replicates (Blocks). Between flowering and seed fill six upper canopy leaves were measured in each plot. The data collector measured each block at multiple times so that we had a wide range of light intensities and times of day.

Lets get started!

#### Import required Liraries
First, lets load the libraries that we will need. If you haven't installed those packages already, please install them first.
```{r}
library(PhotosynQ)
library(broom)
library(stringr)
library(dplyr)
```

#### Get Data from PhotosynQ
Now, we need to get the Data from the PhotosynQ platform. More detailed instructions about how to import project data into R studio can be found in the "Import PhotosynQ Data into R" tutorial.
```{r}
# Get data from PhotosynQ
ID <- 243
df <- PhotosynQ::getProject("john.doe@domain.com", ID)

# Create data-frames with only the submitted data and the Top leaves
chlorophyll <- subset(df$`Chlorophyll content (SPAD) I`, status == "submitted" & Leaf.location == "Top")
photosynthesis <- subset(df$`The One Protocol (Phi2, PSI, NPQ) II`, status == "submitted" & Leaf.location == "Top")

# View the data frames
View(chlorophyll)
View(photosynthesis)

# We are calculating the square root of the light intensity (PAR)
photosynthesis$sqrtPAR <- sqrt(photosynthesis$light_intensity)

# We translate the date into a number (0 to 24)
photosynthesis$TimeOfDay <- as.POSIXlt(photosynthesis$time)$hour + as.POSIXlt(photosynthesis$time)$min/60 + as.POSIXlt(photosynthesis$time)$sec/3600

```

***

### One Way ANOVA
First, we will go thru and analyze the differences in each PhotosynQ
parameter using simple One-Way ANOVA.

```{r}
SPAD1 <- aov(SPAD ~ Variety., chlorophyll)
summary(SPAD1)
```

```{r}
plot(SPAD ~ Variety., chlorophyll)
```

```{r}
plot(SPAD1$fitted,SPAD1$res,xlab="Fitted",ylab="Residuals")
```

```{r}
TukeyHSD(SPAD1, conf.level = 0.95) 
```

```{r}
Phi21 <- aov(Phi2 ~ Variety., photosynthesis)
summary(Phi21)
```

```{r}
plot(Phi2 ~ Variety., photosynthesis)
```

```{r}
plot(Phi21$fitted,Phi21$res,xlab="Fitted",ylab="Residuals")
```

```{r}
TukeyHSD(Phi21, conf.level = 0.95)
```

```{r}
PhiNPQ1 <- aov(PhiNPQ ~ Variety., photosynthesis)
summary(PhiNPQ1)
```

```{r}
plot(PhiNPQ ~ Variety., photosynthesis)
```

```{r}
plot(PhiNPQ1$fitted,PhiNPQ1$res,xlab="Fitted",ylab="Residuals")
```

```{r}
TukeyHSD(PhiNPQ1, conf.level = 0.95)
```

```{r}
PhiNO1 <- aov(PhiNO ~ Variety., photosynthesis)
summary(PhiNO1)
```

```{r}
plot(PhiNO ~ Variety., photosynthesis)
```

```{r}
plot(PhiNO1$fitted,PhiNO1$res,xlab="Fitted",ylab="Residuals")
```

```{r}
TukeyHSD(PhiNO1, conf.level = 0.95)
```

Using One-Way ANOVA, we found significant differences in PhiNPQ between varieties. PhiNPQ was significantly greater in Tutti than in Sy4045 and Pan7049. We did not identify any signficant differences in SPAD, Phi2 or PhiNO.

***

## Multivariate Analysis

In the next set of analyses below, we will use a multiple linear regression model to account for the factors that effect photosynthesis measurements. By controlling for these covariates we hope to identify additional varietal differences that were not visible above the noise of differing light intensities and measurement times from the above analysis.

In our data set, Blocks are labelled 1 to 4. We need to treat Block as a categorical variable and not a numerical variable

```{r}
chlorophyll$Block <- factor(chlorophyll$Block, ordered = TRUE)
```

We do not expect light intensity or time of day to affect SPAD measurements, so in this model we add Block as a covariate

```{r}
SPAD2 <- aov(SPAD ~ Block + Variety., chlorophyll)
summary(SPAD2)
```

```{r}
plot(SPAD2$fitted,SPAD2$res,xlab="Fitted",ylab="Residuals")
```

```{r}
coef(summary.lm(SPAD2))
```

```{r}
TukeyHSD(SPAD2, which = "Variety.")
```

When analyzing photosynthetic parameters (Phi2, PhiNPQ, PhiNO, qL, NPQt, LEF), we should include both light intensity (PAR) and time of day. Because the effect of light intensity is not linear, we use the square root of light intensity (sqrtPAR) rather than the raw PAR.

```{r}
Phi22 <- aov(Phi2 ~ Block + sqrtPAR + TimeOfDay + Variety., photosynthesis)
summary(Phi22)
```

```{r}
plot(Phi22$fitted,Phi22$res,xlab="Fitted",ylab="Residuals")
```

```{r}
coef(summary.lm(Phi22))
```

```{r}
TukeyHSD(Phi22, which = "Variety.")
```

We see from the output above that sqrtPAR, Block, and Variety had a significant affect on Phi2. This is different from the One-Way ANOVA we conducted above, where there were no significant differences between the Phi2 of different varieties.

Now we have generated new unique coeffcients for Sy4045, Pan 7049, and Pan 7351. To calculate adjusted Phi2 values for each Variety we do the following:

1.  Determine the mean of Tutti. This mean has not changed from the One-Way ANOVA we ran before. It appears that the mean is about 0.28 
2.  To calculate the adjusted Phi2 for Sy4045, we add the mean of
Tutti to the coeffcient for Variety B (0.06). `0.28 + 0.06 = 0.34`

Based on the results of this analysis, we see that both Sy4045 and Pan 7049 have significantly greater Phi2 than Tutti.

```{r}
PhiNPQ2 <- aov(PhiNPQ ~ Block + sqrtPAR + TimeOfDay + Variety., photosynthesis)
summary(PhiNPQ2)
```

```{r}
plot(PhiNPQ2$fitted,PhiNPQ2$res,xlab="Fitted",ylab="Residuals")
```

```{r}
TukeyHSD(PhiNPQ2, which = "Variety.")
```



In the analysis of PhiNPQ, we actually end up with the same basic results that we got from the One-Way ANOVA above, with Tutti having a significantly higher PhiNPQ than Sy4045 and Pan 7049. However, we see that by including key covariates, the F statistic increased from 3.76 to 5.95 and the p-value decreased from 0.014 to 0.001.

```{r}
PhiNO2 <- aov(PhiNO ~ Block + sqrtPAR + TimeOfDay + Variety., photosynthesis)
summary(PhiNO2)
```

```{r}
plot(PhiNO2$fitted,PhiNO2$res,xlab="Fitted",ylab="Residuals")
```



```{r}
coef(summary.lm(PhiNO2))
```

```{r}
TukeyHSD(PhiNO2, which = "Variety.")
```

Similar to SPAD, there were no significant differences when using multivariate analysis to analyze PhiNO.

***

### Conclusions
When we used a multivariate analysis to account for the factors that affect PhotosynQ parameters, we were able to identify differences that were not apparent using One-Way ANOVA. This can be critical when interpreting your results. In this example, using One-Way ANOVA we know that PhiNPQ was greater in Tutti than Sy4045 and Pan 7049. However, we cannot determine the cause of that increase. When we used the more sophisticated multivariate analysis, we now see that, Phi2 was also greater in Sy4045 and Pan 7049 than in Tutti.

Therefore, we now know that Tutti was diverting more light energy away from photosystem II, which is what accounted for the greater PhiNPQ. In the next tutorial we will use correlation matrices and mixed effect models to determine how PhotosynQ parameters are related to crop productivity.
