背景
这个问题有点复杂,先介绍一下背景。要生成物种生死表(L 表)的示例,我建议使用 dd_sim()
包中的 DDD
函数。
library(DDD)
library(tidyverse)
library(picante)
result <- dd_sim(c(0.2, 0.1, 20), 10)
# with birth rate 0.2, death rate 0.1, carrying capacity 20 and overall 10 million years.
L <- result$L
L
[,1] [,2] [,3] [,4]
[1,] 10.0000000 0 -1 -1.0000000
[2,] 10.0000000 -1 2 2.7058965
[3,] 8.5908774 2 3 6.6301616
[4,] 8.4786474 3 4 3.3866813
[5,] 8.4455262 -1 -5 -1.0000000
[6,] 8.3431071 4 6 3.5624756
[7,] 5.3784683 2 7 0.6975934
[8,] 3.8950593 6 8 -1.0000000
[9,] 1.5032100 -5 -9 -1.0000000
[10,] 0.8393589 7 10 -1.0000000
[11,] 0.6118985 -5 -11 -1.0000000
L 表有 4 列:
第四个元素等于 -1,则该物种仍然存在。
我做了什么
有了这个 L 表,我现在就有了一个现存的社区。我想计算它的系统发育多样性(也称为 Faith 指数)
使用
DDD
和 picante
函数我可以做到:# convert L table into community data matrix
comm = as.data.frame(L) %>% dplyr::select(V3:V4) %>%
dplyr::rename(id = V3, pa = V4) %>%
dplyr::mutate(id = paste0("t",abs(id))) %>%
dplyr::mutate(pa = dplyr::if_else(pa == -1, 1, 0)) %>%
dplyr::mutate(plot = 0) %>%
dplyr::select(plot, pa, id) %>%
picante::sample2matrix()
# convert L table into phylogeny
phy = DDD::L2phylo(L, dropextinct = T)
# calculate Faith's index using pd() function
Faith = picante::pd(comm,phy)
问题
虽然我达到了我的目标,但这个过程似乎是多余的和耗时的。我必须来回转换我原来的 L 表,因为我必须使用现有的函数。
根据定义,信仰指数基本上是社区 总系统发育分支长度的总和,所以我的问题是:
先谢谢了!
最佳答案
您可以简单地使用 phy$edge.length
生成的 phylo
对象的 DDD::L2phylo
组件:
## Measuring the sum of the branch lengths from `phy`
sum_br_length <- sum(phy$edge.length)
sum_br_length == Faith$PD
# [1] TRUE
## Measuring the sum of the branch length from `L`
sum_br_length <- sum(DDD::L2phylo(L, dropextinct = TRUE)$edge.length)
sum_br_length == Faith$PD
# [1] TRUE
还有一些有趣的微基准测试:
library(microbenchmark)
## Function 1
fun1 <- function(L) {
comm = as.data.frame(L) %>% dplyr::select(V3:V4) %>%
dplyr::rename(id = V3, pa = V4) %>%
dplyr::mutate(id = paste0("t",abs(id))) %>%
dplyr::mutate(pa = dplyr::if_else(pa == -1, 1, 0)) %>%
dplyr::mutate(plot = 0) %>%
dplyr::select(plot, pa, id) %>%
picante::sample2matrix()
# convert L table into phylogeny
phy = DDD::L2phylo(L, dropextinct = T)
# calculate Faith's index using pd() function
Faith = picante::pd(comm,phy)
return(Faith$PD)
}
## Function 2
fun2 <- function(L) {
phy <- DDD::L2phylo(L, dropextinct = T)
return(sum(phy$edge.length))
}
## Function 3
fun3 <- function(L) {
return(sum(DDD::L2phylo(L, dropextinct = TRUE)$edge.length))
}
## Do all of them give the same results
fun1(L) == Faith$PD
# [1] TRUE
fun2(L) == Faith$PD
# [1] TRUE
fun3(L) == Faith$PD
# [1] TRUE
## Which function fastest?
microbenchmark(fun1(L), fun2(L), fun3(L))
# Unit: milliseconds
# expr min lq mean median uq max neval
# fun1(L) 6.486462 6.900641 8.273386 7.445334 8.667535 16.888429 100
# fun2(L) 1.627854 1.683204 2.215531 1.771219 2.229408 9.522366 100
# fun3(L) 1.630635 1.663181 2.229206 1.859733 2.448196 7.573001 100
关于r - 从物种生死表计算总系统发育分支长度的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58853816/