You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中实现数据框与系统发育树(phylo/Newick)的互转?

用R实现系统发育树的表格与标准格式互转

1. 表格格式转phylo/Newick格式

首先定义输入的亲子关系数据框:

phylo_df <- data.frame(
  node   = c("t1", "t2", "t3", "t4", "t5", "A", "B", "C"),
  parent = c("A",  "A",  "B",  "C",  "C",  "B", "D", "D"),
  length = c(0.7, 0.08, 0.32, 0.24, 0.07, 0.91, 0.7, 0.95)
)

# 查看数据框结构
phylo_df

输出结果:

node parent length
1 t1 A 0.70
2 t2 A 0.08
3 t3 B 0.32
4 t4 C 0.24
5 t5 C 0.07
6 A B 0.91
7 B D 0.70
8 C D 0.95

使用data.tree包将表格转换为phylo对象(ape包标准格式),并生成Newick字符串:

library(ape)
library(ggtree)
library(data.tree)

# 将数据框转换为树形结构
tree_struct <- FromDataFrameNetwork(phylo_df[, c("parent", "node", "length")])

# 转成ape包的phylo对象
phylo_tree <- as.phylo(tree_struct)

# 输出对应的Newick字符串
write.tree(phylo_tree)
# 输出: ((t5:0.07,t4:0.24)C:0.95,(t3:0.32,(t2:0.08,t1:0.7)A:0.91)B:0.7)D;

# 绘图展示系统发育树
ggtree(phylo_tree) +
  geom_tiplab(color='firebrick') +
  geom_nodelab(aes(x=branch, label=label, subset=nchar(label)>0), geom="label") +
  theme_tree2()

系统发育树

2. 操作phylo对象添加外类群

直接在phylo对象上修改,添加外类群t6并构建新根节点E:

# 复制原phylo对象
tree2 <- phylo_tree

# 添加外类群t6,分支长度设为0.5
tree2 <- bind.tree(tree2, read.tree(text="t6:0.5"), position=0, interactive=FALSE)

# 给新根节点命名为E
tree2$node.label[length(tree2$node.label)] <- "E"
# 调整原根节点D的分支长度为0.5
tree2$edge.length[which(tree2$edge[,2] == Ntip(tree2)+1)] <- 0.5

# 输出新的Newick字符串
write.tree(tree2)
# 输出: (((t5:0.07,t4:0.24)C:0.95,(t3:0.32,(t2:0.08,t1:0.7)A:0.91)B:0.7)D:0.5,t6:0.5)E;

# 绘图展示扩展后的系统发育树
ggtree(tree2) +
  geom_tiplab(color='firebrick') +
  geom_nodelab(aes(x=branch, label=label, subset=nchar(label)>0), geom="label") +
  theme_tree2()

扩展后的系统发育树

3. phylo对象转回表格格式

将修改后的phylo对象重新转换为亲子关系表格:

# 将phylo对象转回data.tree结构
tree_struct2 <- as.Node(tree2)

# 转换为亲子关系表格
phylo_df_new <- ToDataFrameNetwork(tree_struct2, "length")
# 调整列名顺序与原表格一致
colnames(phylo_df_new) <- c("parent", "node", "length")
phylo_df_new <- phylo_df_new[, c("node", "parent", "length")]

# 查看最终表格
phylo_df_new

输出结果:

node parent length
1 t1 A 0.70
2 t2 A 0.08
3 t3 B 0.32
4 t4 C 0.24
5 t5 C 0.07
6 A B 0.91
7 B D 0.70
8 C D 0.95
9 D E 0.50
10 t6 E 0.50

内容的提问来源于stack exchange,提问作者Moehrengulasch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:13:12