我有一个包含许多提示和内部节点的系统发育树。我有一个树中的节点 ID 列表。这些是单独表格的一部分。我想在表中添加一个新列,children。为了获得后代(节点和提示),我使用了 phangorn::Descendants(tree, NODEID, type = 'all')
。我可以添加长度以获得后代的数量。例如,
phangorn::Descendants(tree, 12514, type = 'all')
[1] 12515 12517 12516 5345 5346 5347 5343 5344
length(phangorn::Descendants(tree, 12514, type = 'all'))
[1] 8
我想非常简单地获取我的数据框“节点”中的列,并使用 length(phangorn::Descendants(tree, 12514, type = 'all'))
上面的函数来根据输入节点在数据框中创建一个新列。
这是一个例子:
tests <- data.frame(nodes=c(12551, 12514, 12519))
length(phangorn::Descendants(tree, 12519, type = 'all'))
[1] 2
length(phangorn::Descendants(tree, 12514, type = 'all'))
[1] 8
length(phangorn::Descendants(tree, 12551, type = 'all'))
[1] 2
tests$children <- length(phangorn::Descendants(tree, tests$nodes, type = 'all'))
tests
nodes children
1 12551 3
2 12514 3
3 12519 3
如上所示,children的数量是data.frame的长度,并不是上面计算的实际children的数量。应该是:
tests
nodes children
1 12551 2
2 12514 8
3 12519 2
如果您对我如何使此行为符合预期有任何提示或想法,那就太好了。我有一种感觉,我必须使用 apply() 或者我需要在使用 length() 函数之前在内部建立索引。提前谢谢你。
最佳答案
你非常接近!这是一个使用 sapply
的快速解决方案!还有更多选择,但这个似乎符合您问题的结构!
生成一些数据
library(ape)
ntips <- 10
tree <- rtree(ntips)
targetNodes <- data.frame(nodes=seq(ntips+1, ntips+tree$Nnode))
请注意,我将所有相关节点存储在 targetNodes
对象中。这相当于您问题中的以下对象:
tests <- data.frame(nodes=c(12551, 12514, 12519))
使用应用
现在,让我们使用 sapply
在 targetNodes
中的所有相关节点上重复相同的操作:
targetNodes$children<- sapply(targetNodes$nodes, function(x){
length(phangorn::Descendants(tree, x, type = 'all'))
})
我通过在 targetNodes
中创建一个新列来保存我们的 sapply
函数的输出。
祝你好运!
关于r - 在树文件类 Phylo 的列上使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72779015/