library(tidyverse)
library(magrittr)
library(readxl)
library(openxlsx)
library(lubridate)
library(cowplot)
library(lsmeans)
library(lme4)
library(lmerTest) # import lmerTest *AFTER* lme4

Define functions for histogram and QQ plot:

norm.hist <- function(data.vec, xlab){ # function to draw normal density plot
  hist.x <- sort(na.omit(data.vec))
  hist.seq <- seq(min(hist.x), max(hist.x), length.out=length(hist.x))
  hist.d <- dnorm(hist.seq, mean(hist.x), sd(hist.x))
  df.hist <- data.frame(x = hist.x, seq = hist.seq, d = hist.d)
  ggplot(df.hist) + geom_histogram(aes(x = x, y = ..density..)) +
    geom_line(aes(x = seq, y = d), colour = "red", size = 1.2) +
    labs(x = xlab, y = "Frequency")
}

draw.qq <- function(data.vec, xlab){ # function to draw QQ-plot
  y <- sort(na.omit(data.vec))
  probs <- (1:length(y))/(length(y) + 1)
  norm.quantiles = qnorm(probs, mean(y), sd(y))
  df.qq <- data.frame(y = y, nq = norm.quantiles)
  p <- ggplot(df.qq, aes(x = nq, y = y)) + geom_point() + 
    geom_abline(slope = 1, intercept = 0, color='red') +
    labs(x = "Normal Quantiles", y = xlab) +
    geom_abline(slope = 1, intercept = 0, color='red')
}

Preparation of Wenjie_second experiment W2 flowering data.

# Read in indiv plant data from excel
in_name <- "wenjie_second-2020-04-23.xlsx"
infile <- file.path(path.expand("~"),"FlrGWAS","Flr_Data", in_name)
df <- read_excel(infile, sheet = 1)
df2 <- df %>% rename(RefPop     = GenoNum,
                     Experiment = ExptNum) %>% 
  mutate(PltNum  = as.factor(PltNum),
         RepNum  = as.factor(RepNum),
         RackNum = as.factor(RackNum)) %>% 
  select(Experiment, FlrAge, PltNum, RefPop, RepNum, RackNum, Alive2)

names(df2)
## [1] "Experiment" "FlrAge"     "PltNum"     "RefPop"     "RepNum"    
## [6] "RackNum"    "Alive2"
(NumPlanted <- nrow(df2))
## [1] 2304

Prepare data:

df2$Alive2 <- ifelse(df2$Alive2 == 2, 1, df2$Alive2) # Alive at time 2
df2 <- filter(df2, Alive2 >= 0)
NumSurvived <- sum(df2$Alive2)

df3 <- filter(df2, FlrAge > 0) # Exclude if FlrAge is nonpositive
NumFlowered <- nrow(df3)
glimpse(df3)
## Rows: 1,603
## Columns: 7
## $ Experiment <chr> "W2", "W2", "W2", "W2", "W2", "W2", "W2", "W2", "W2", "W2"…
## $ FlrAge     <dbl> 12, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14…
## $ PltNum     <fct> 2175, 1407, 769, 2119, 1735, 967, 1845, 1233, 898, 902, 12…
## $ RefPop     <chr> "RP452", "RP452", "RP506", "RP139", "RP139", "RP139", "RP1…
## $ RepNum     <fct> 6, 4, 3, 6, 5, 3, 5, 4, 3, 3, 4, 4, 6, 3, 1, 5, 5, 5, 1, 1…
## $ RackNum    <fct> 23, 15, 9, 23, 19, 11, 20, 13, 10, 10, 14, 14, 22, 11, 3, …
## $ Alive2     <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
(maxFlrAge <- max(df3$FlrAge))
## [1] 35
(num_genos <- n_distinct(df3$RefPop, na.rm = TRUE)) # Number of flowering genotypes)
## [1] 356

Now, histogram and QQ-plot with original and log-transformed Flower_Age:

p1 <- norm.hist(df3$FlrAge, "Flower_Age")
p2 <- draw.qq(df3$FlrAge, "Flower_Age")

plot_grid(p1, p2, nrow = 1, labels = c("A", "B")) # join & print figures
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

The original flowering distribution deviates slightly from normality

df3 <- df3 %>% mutate(LogFlrAge = log10(FlrAge))
names(df3)
## [1] "Experiment" "FlrAge"     "PltNum"     "RefPop"     "RepNum"    
## [6] "RackNum"    "Alive2"     "LogFlrAge"

p1 <- norm.hist(df3$LogFlrAge, "Log10FlrAge")
p2 <- draw.qq(df3$LogFlrAge, "Log10FlrAge")

plot_grid(p1, p2, nrow = 1, labels = c("A", "B")) # join & print figures
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

The log transformed flowering distribution has slightly improved normality. For consistency among experiments, we will analyze this.


Save data file for GxE analysis

df3.W2 <- df3 %>% select(Experiment, RefPop, RackNum, LogFlrAge)
file_name <- "W2_plants_LogFlr.txt"
out_name <- file.path(path.expand("~"),"FlrGWAS", "output", file_name)
write_tsv(df3.W2, out_name)

Mean flowering time in Wenjie’s second experiment (original scale):

(FlrInfo <- select(df3, FlrAge) %>% 
  summarize_all(list(mean = mean, sd = sd), na.rm = TRUE))
## # A tibble: 1 x 2
##    mean    sd
##   <dbl> <dbl>
## 1  22.8  4.63

Summary: The original number of plants was 2304. Of these, 1644 survived until the end of cold treatment. The number of flowering plants was 1603. Surviving plants that did not flower total 41, or 2.4939%. Latest flowering ocurred at 35 days after cold treatment. The number of genotypes that flowered is 356. Average flowering age is 22.806 +/- 0.1156.


Compute random effects ANOVA:

# See review on formulas: 
# https://conjugateprior.org/2013/01/formulae-in-r-anova/

# Excluding RepNum to allow model convergence 

mod <- lmer(LogFlrAge ~ (1 | RefPop) +  (1 | RackNum), data=df3)
summary(mod)
## Linear mixed model fit by REML. t-tests use Satterthwaite's method [
## lmerModLmerTest]
## Formula: LogFlrAge ~ (1 | RefPop) + (1 | RackNum)
##    Data: df3
## 
## REML criterion at convergence: -3723
## 
## Scaled residuals: 
##    Min     1Q Median     3Q    Max 
## -3.980 -0.455  0.055  0.533  3.602 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  RefPop   (Intercept) 0.004398 0.0663  
##  RackNum  (Intercept) 0.000531 0.0231  
##  Residual             0.003719 0.0610  
## Number of obs: 1603, groups:  RefPop, 356; RackNum, 24
## 
## Fixed effects:
##             Estimate Std. Error      df t value Pr(>|t|)    
## (Intercept)   1.3534     0.0061 48.2913     222   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Notice that RepNum was excluded to enable model convergence


Get BLUPs

blup <- ranef(mod) # get BLUPs
RP.blup <- as.vector(blup$RefPop[, 1]) # vector of BLUPs for each genotype

# get RefPop means
df.byRefPop <- df3 %>% group_by(RefPop)
RP.means <- summarize(df.byRefPop, RPmean = mean(LogFlrAge))
RP_IDs <- RP.means$RefPop              # vector of RefPop IDs
RP.means <- as.vector(RP.means$RPmean) #vector of genotype means

df.mn.blup <- tibble(ID = RP_IDs, RP_meanW2 = RP.means, RP_blupW2 = RP.blup)
dim(df.mn.blup)
## [1] 356   3

cor(RP.means, RP.blup) # Correlation between BLUPs and RefPop means
## [1] 0.9861

Conclusion: BLUP estimates are highly correlated with genotype means.


# histogram of BLUPs:
norm.hist(df.mn.blup$RP_blupW2, "LogFlrAge BLUPs")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.


#Output BLUP data frame
file_name <- "Wenjie_second_LogFlr_BLUPS.txt"
out_name <- file.path(path.expand("~"),"FlrGWAS", "output", file_name)
write_tsv(df.mn.blup, out_name)

Variance components, Coefficient of Determination, & Heritability

Residual Var Comp is taken from summary() printout. Change manually if the data or model change.

# Residual variance component for this model only
# Change this value if the model or data are changed

vc.Resid <- 0.003719 # This is model specific! ***

Next, compute R-squared and Heritability

vcs <- summary(mod)$varcor
(vc.RefPop <- vcs$RefPop[1,1])
## [1] 0.004398
(vc.RackNum  <- vcs$RackNum[1,1])
## [1] 0.0005315
(vc.Explained <- sum(vc.RefPop + vc.RackNum)) # total of variance components
## [1] 0.004929
(vc.Tot <-  (vc.Explained + vc.Resid))
## [1] 0.008648
(R2 <- vc.Explained / vc.Tot) # R-squared
## [1] 0.57
(H2 <- vc.RefPop / vc.Tot) # heritability
## [1] 0.5085

Conclusions:

The model explains 56.9974% of variation in log-transformed age at first flowering. Heritability of LogFlrAge = 50.8523%.