-
Notifications
You must be signed in to change notification settings - Fork 1
/
pglsPagel.Rmd
74 lines (62 loc) · 2.63 KB
/
pglsPagel.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
---
title: "pgls.seYPagel"
author: "Walker M"
date: "2023-07-06"
output: html_document
---
Packages
```{r}
library(phytools)
library(geiger)
```
Save function to local environment
```{r}
modPgls.SEy = function (model, data, corClass = corBrownian, tree, se = NULL,
method = c("REML", "ML"), interval = c(0, 1000), corClassValue=1, sig2e=NULL, ...)
{
Call <- match.call()
corfunc <- corClass
spp <- rownames(data)
data <- cbind(data, spp)
if (is.null(se))
se <- setNames(rep(0, Ntip(tree)), tree$tip.label)[spp]
else se <- se[spp]
lk <- function(sig2e, data, tree, model, ve, corfunc, spp) {
tree$edge.length <- tree$edge.length * sig2e
ii <- sapply(1:Ntip(tree), function(x, e) which(e ==
x), e = tree$edge[, 2])
tree$edge.length[ii] <- tree$edge.length[ii] + ve[tree$tip.label]
vf <- diag(vcv(tree))[spp]
w <- varFixed(~vf)
COR <- corfunc(corClassValue, tree, form = ~spp, ...)
fit <- gls(model, data = cbind(data, vf), correlation = COR,
method = method, weights = w)
-logLik(fit)
}
if (is.null(sig2e)) {
fit <- optimize(lk, interval = interval, data = data, tree = tree,
model = model, ve = se^2, corfunc = corfunc, spp = spp)
sig2e=fit$minimum
}
tree$edge.length <- tree$edge.length * sig2e
ii <- sapply(1:Ntip(tree), function(x, e) which(e == x),
e = tree$edge[, 2])
tree$edge.length[ii] <- tree$edge.length[ii] + se[tree$tip.label]^2
vf <- diag(vcv(tree))[spp]
w <- varFixed(~vf)
obj <- gls(model, data = cbind(data, vf), correlation = corfunc(corClassValue,
tree, form = ~spp, ...), weights = w, method = method)
obj$call <- Call
obj$sig2e <- sig2e
obj
}
#Internal function
pglsSEyPagelToOptimizeLambda=function(lambda,model,data,tree,...) {
-logLik(modPgls.SEy(model=model,data=data,tree=tree,corClassValue=lambda,corClass=corPagel,fixed=T,...)) #Returns -logLikelihood of the pgls.SEy model with lambda fixed to the value of the lambda argument. sig2e will be optimized within modPgls.SEy unless given as an argument here
}
#Function intended for users
pglsSEyPagel=function(model, data, tree, lambdaInterval=c(0,1),...){
optimizedModel=optimize(pglsSEyPagelToOptimizeLambda,lambdaInterval,model=model,data=data,tree=tree,...) #Optimizes lambda in the lambdaInterval using the pglsSEyPagelToOptimizeLambda function
return(modPgls.SEy(model=model,data=data,tree=tree,corClass=corPagel,fixed=T,corClassValue=optimizedModel$minimum,...)) #Returns the final model fit
}
```