-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiversity.rmd
386 lines (242 loc) · 7.08 KB
/
diversity.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
---
title: Diversity calculation
author: Masatoshi Katabuchi
date: "2020/11/2 (updated: `r Sys.Date()`)"
output:
#rmdformats::material
html_document:
fig_caption: yes
theme: spacelab #readable #sandstone #spacelab #flatly
highlight: pygments #tango #kate
toc: TRUE
toc_depth: 2
number_sections: TRUE
toc_float:
collapsed: TRUE
smooth_scroll: TRUE
toc: true
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(echo=TRUE,
warning=FALSE,
cache=FALSE,
message=FALSE)
htmltools::tagList(rmarkdown::html_dependency_font_awesome())
```
<a href="https://twitter.com/mattocci"><i class="fa fa-twitter fa-1x"></i> Twittter</a>
<a href="https://github.com/mattocci27/"><i class="fa fa-github fa-1x"></i> Github</a>
<a href="mailto:[email protected]"><i class="fa fa-envelope fa-1x"></i> Email</a>
Course materials for 2020-11-2 AFEC at XTBG.
# Prerequisites
Did you install `picante` and `FD`?
```{r, eval = F}
install.packages("picante")
install.packages("FD")
```
It's better if you have those packages too.
```{r, eval = F}
install.packages("tidyverse")
install.packages("rmarkdown")
install.packages("DT")
```
Load pacakges.
```{r}
library(picante)
library(FD)
library(tidyverse)
library(rmarkdown)
```
# Data
## Community
```{r}
samp <- read_csv("./gr3/group_3.csv")
DT::datatable(samp)
samp_mat <- as.matrix(samp[, -1])
rownames(samp_mat) <- samp$Sample_code
samp_mat
```
## Phylogeny
```{r, fig.height = 20}
phylo <- read.tree("/dummy_tree.newick")
plot(phylo)
```
## Traits
| Abbreviation | Trait | Unit |
| ------------ | ------------------------------------------ | ----------------- |
| LMA | Leaf mass per area | g m^-2^ |
| LL | Leaf lifespans (longevity) | months |
| Amass | Maximum photosynthetic rates per unit mass | nnoml g^-1^ s^-^1 |
| Rmass | Dark resperation rates per unit mass | nnoml g^-1^ s^-^1 |
| Nmass | Leaf nitrogen per unit mass | % |
| Pmass | Leaf phosphorus per unit mass | % |
| WD | Wood density | g cm^-3^ |
| SM | Seed dry mass | mg |
```{r}
trait <- read_csv("./data/dummy_trait.csv")
# trait <- read.csv("./data/dummy_trait.csv") is fine too.
DT::datatable(trait)
```
## Check the histograms of trait values first
```{r}
trait_long <- trait %>%
gather(trait, val, 2:9)
ggplot(trait_long, aes(x = val)) +
geom_histogram(position = "identity") +
facet_wrap(~ trait, scale = "free")
```
Probably we can do log-transformation for all the traits except for WD.
```{r}
trait2 <- trait %>%
mutate(logLMA = log(LMA),
logLL = log(LL),
logAmass = log(Amass),
logRmass = log(Rmass),
logNmass = log(Nmass),
logPmass = log(Pmass),
logSM = log(SM)) %>%
dplyr::select(sp, logLMA, logLL, logAmass, logRmass, logNmass, logPmass, WD, logSM)
DT::datatable(trait2)
```
```{r}
trait2 %>%
gather(trait, val, 2:9) %>%
ggplot(., aes(x = val)) +
geom_histogram(position = "identity") +
facet_wrap(~ trait, scale = "free")
```
# Fisrt-order metrics (without phylogeny or traits)
## Species richness, Beta diversity metrics
Skip
## Nonmetric Multidimensional Scaling (NMDS)
```{r}
res_mds <- metaMDS(samp_mat)
plot(res_mds)
```
We can use the function ordiplot and orditorp to add text to the plot in place of points to make some more sence.
```{r}
ordiplot(res_mds, type = "n")
orditorp(res_mds,display="species",col="red",air=0.01)
orditorp(res_mds,display="sites",cex=1.25,air=0.01)
```
# Phylogenetic metrics
## Branch length based metric
### PD
```{r}
res_pd <- pd(samp_mat, phylo)
res_pd
rownames(res_pd) %>%
str_split("_")
rownames(res_pd) %>%
str_split("_") %>%
sapply(., "[[", 1)
rownames(res_pd) %>%
str_split("_") %>%
sapply(., "[[", 1) %>%
tibble(forest = .) %>%
mutate(pd = res_pd$PD)
rownames(res_pd) %>%
str_split("_") %>%
sapply(., "[[", 1) %>%
tibble(forest = .) %>%
mutate(pd = res_pd$PD) %>%
ggplot(., aes(x = forest, y = pd)) +
geom_boxplot()
```
You can always see the help.
```{r, eval = F}
?pd
```
## Distance based metric
`cophenetic()` creates distance matrices based on phylogenetic trees. Let's see the first 5 species.
```{r}
cophenetic(phylo)[1:5, 1:5]
```
### MPD
$MPD = \frac{1}{n} \Sigma^n_i \Sigma^n_j \delta_{i,j} \; i \neq j$, where
$\delta_{i, j}$ is the pairwised distance between species *i* and *j*
```{r}
res_mpd <- mpd(samp_mat, cophenetic(phylo))
res_mpd
```
The above vector shows MPD for each site.
### MNTD
$MNTD = \frac{1}{n} \Sigma^n_i min \delta_{i,j} \; i \neq j$, where $min \delta_{i, j}$ is the minimum distance between species *i* and all other species in the community.
```{r}
res_mntd <- mntd(samp_mat, cophenetic(phylo))
res_mntd
```
# Functional metrics
## Community weighted means (CWM)
$$
CWM_i = \frac{\sum_{j=1}^n a_{ij} \times t_{j}}{\sum_{j=1}^n a_{ij}}
$$
```{r}
tmp <- trait2 %>%
filter(sp %in% colnames(samp_mat))
tmp
(ab <- apply(samp_mat, 1, sum))
# inner product
(CWS <- samp_mat %*% as.matrix(tmp[,-1]))
```
```{r}
(CWM <- CWS / ab)
```
## Distance based metrics
### Prepare a trait distance matrix
We have a `data.fame` of traits. First we need to prepare a trait matrix, then a distance matrix based on trait values.
```{r}
trait_mat0 <- as.matrix(trait2[, -1])
rownames(trait_mat0) <- trait2$sp
```
Let's see a subset of the trait matrix
```{r}
trait_mat0[1:5, 1:5]
```
Then, we will make trait distance matrix based on the Euclidean distance. There are
other distance measures, for example [Gower's Distance](https://www.rdocumentation.org/packages/gower/versions/0.2.1/topics/gower_dist), but we focus on the Euclidean distance today.
Before calulating distance, we need to make sure unit change in ditances have
same for different traits. We will scale trait values so that then have mean = 0
and SD = 1. (e.g., $(X_i - \mu) / \sigma$)
```{r}
trait_mat <- scale(trait_mat0)
par(mfrow = c(2, 2))
hist(trait_mat0[, "logLMA"])
hist(trait_mat[, "logLMA"])
hist(trait_mat0[, "WD"])
hist(trait_mat[, "WD"])
par(mfrow = c(1, 1))
```
Now we can make a trait distance matirx.
```{r}
trait_dm <- as.matrix(dist(trait_mat))
```
Let's see the first 5 species.
```{r}
trait_dm[1:5, 1:5]
```
### MPD
```{r}
mpd(samp_mat, trait_dm)
ses.mpd(samp_mat, trait_dm)
```
### MNTD
```{r}
mntd(samp_mat, trait_dm)
```
## Branch length based metric
### FD
We will make a functional dendrogram using clustring methods. We use [UPGMA](https://en.wikipedia.org/wiki/UPGMA) in
this example.
```{r, fig.width = 15, fig.height = 15}
t_clust <- hclust(dist(trait_mat), method = "average")
plot(t_clust)
```
### More functional diversity metrics
```{r, eval = TRUE}
res_fd <- dbFD(trait_mat[colnames(samp_mat), ], samp_mat)
res_fd
```
# Computing Environment
```{r}
devtools::session_info()
```