【问题标题】:Setting the edge.lenth in a phylo object using a variable in a data.frame使用 data.frame 中的变量在 phylo 对象中设置 edge.length
【发布时间】:2018-11-26 18:07:43
【问题描述】:

我想使用 data.frame 中的变量在 phylo 对象中设置“edge.length”。 phylo 对象中的“node.label”“tip.label”对应于 data.frame 中的行名。如何使用 data.frame 中的变量设置 edge.length,同时确保数据正确匹配?在下面的代码中,它位于步骤 3 中。我希望匹配 edge.length,以便 node.label 或 tip.label 匹配 data.frame 中的 row.name。

## R code:
## load ape
library(ape)
## 1. A phylo object:
library(data.tree)

A1  <- Node$new("A1")
B1  <- A1$AddChild("B1")
C1  <- B1$AddChild("C1")
D1  <- C1$AddChild("D1")
E1 <- C1$AddChild("E1")
F1 <- E1$AddChild("F1")
G1 <- E1$AddChild("G1")
H1 <- G1$AddChild("H1")
A1.phylo <- as.phylo.Node(A1)


## 2. A data.frame:
set.seed(1)
df <- as.data.frame(rnorm(7, 5, 3))
names(df) <- "length"
row.names(df) <- c("B1","C1","D1","E1","F1","G1","H1")

## 3. Ad the data to A1.phylo$edge.length
A1.phylo$edge.length <- df$length ## wrong!!!

【问题讨论】:

  • 欢迎来到 SO!请添加您的数据和您尝试过的代码。

标签: r phylogeny ape-phylo


【解决方案1】:

"phylo" 对象中的边长度、尖端标签和节点标签按照它们在边表中出现的顺序进行处理。因此,您应该始终为不同的元素赋予属性,同时确保它们在被赋予之前的顺序正确。例如(对不起,我无法重现您的示例):

set.seed(1)
## A random tree with 6 edges
test_tree <- rtree(4)

## The edge table
test_tree$edge
#     [,1] [,2]
#[1,]    5    1
#[2,]    5    6
#[3,]    6    2
#[4,]    6    7
#[5,]    7    3
#[6,]    7    4

这里的边是连接节点(数字&gt;4)和尖端(数字&lt;5)的所有元素。 您可以使用plot 可视化它们(及其编号):

## Visualising all the elements
plot(test_tree, show.tip.label = FALSE)
edgelabels()
nodelabels()
tiplabels()

所以现在如果你有这样的数据框:

## A random data frame
df <- as.data.frame(rnorm(6))
names(df) <- "length"
## The edges in the "wrong" order
row.names(df) <- sample(1:6)

您可以使用以下方法正确地为行分配属性:

## Get the order of the edges
test_tree$edge.length <- df$length[sort(rownames(df))]

在这种情况下,排序非常容易,因为df 中的边名称是数字,但逻辑是,test_tree$edge.length 中的第一个元素应该是连接节点 5 到尖端 1 的边的长度,等等。 .

同样,由于您的示例不可重现,因此很难找出问题所在,但我想说您的 df$length 长度不正确。

【讨论】:

  • 谢谢托马斯。我添加了“库(data.tree)”,这应该使它可重现。我正在考虑的情况是您不知道顺序。并且您想将与提示“H1”关联的 edge.length 设置为 data.frame 中行“H1”的值,依此类推。
  • 感谢 Erling,您的示例现在确实有效!您可以查看我给this question 的答案,将边缘表转换为更可解释的数据(即哪个边缘链接到哪个节点)。然后,您可以使用与我在此答案中描述的相同的逻辑来决定您希望将 df$length 传递给 tree$edge.length 的顺序。我希望这是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 2013-07-10
相关资源
最近更新 更多