run_pgls(formula, data, phy)

Phylogenetic generalised least squares (PGLS) with Pagel's lambda estimated by ML. Requires ape and nlme.

statisticsphylogenetics
Args:formula — e.g. y ~ xdata — species as rownamesphy — phylo object
run_pgls <- function(formula, data, phy) {
  if (!requireNamespace("nlme",  quietly = TRUE)) install.packages("nlme")
  if (!requireNamespace("ape",   quietly = TRUE)) install.packages("ape")
  library(nlme); library(ape)
  
  sp <- intersect(rownames(data), phy$tip.label)
  data <- data[sp, ]
  phy  <- keep.tip(phy, sp)
  
  C   <- vcv(phy, corr = TRUE)
  cor <- corPagel(1, phy, fixed = FALSE)
  
  fit <- gls(formula, data = data,
             correlation = cor,
             method = "ML")
  summary(fit)
}