从距离矩阵创建系统发育树(Newick 文件)?

Create Phylogeny Tree (Newick File) from Distance Matrix?

我已经建立了我的基因簇,并且已经计算出测量它们的系统发育关系所需的距离。我使用了一种算法,基本上可以衡量基因簇之间的距离,并在数据框中表示,例如 (Input Example):

BGC1      BGC2     Distance
------------------------------ 
BGC31     BGC34     0.6
BGC34     BGC45     0.7
BGC34     BGC53     0.2
BGC53     BGC31     0.8

x <- data.frame(BGC1 = c('BGC31','BGC34','BGC34','BGC35'), 
                BGC2 = c('BGC34','BGC45','BGC53','BGC51'), 
                distance = c(0.6,0.7,0.2,0.8))

目标: 是否可以仅基于此类数据构建树?我也想为此提供一个 .newick 文件,但我不确定是否可以使用 R。

然而,我已经能够通过 Cytoscape 从这些数据创建网络可视化,但不可能是一棵树。对于这个特定示例还有进一步的建议吗?

再次感谢您的意见:)

按照 user20650 here 评论中的建议,您可以定义如何使用 lower.tri 函数将距离包装到 dist 对象。但是,提供的示例将不起作用,因为它不提供样本之间的成对距离。因此,该解决方案采用您的样本名称,生成随机数据,然后使用 ape 包中的 nj 函数构建树。

# get all sample names
x.names = unique(c(levels(x[, 1]), levels(x[, 2])))
n = length(x.names)

# create all combinations for samples for pairwise comparisons
x2 = data.frame(t(combn(x.names, m = 2)))
# generate random distances
set.seed(4653)
x2$distance = sample(seq(from = 0.1, to = 1, by = 0.05), size = nrow(x2), replace = TRUE)

# prepare a matrix for pairwise distances
dst = matrix(NA, ncol = n, nrow = n, dimnames = list(x.names, x.names))
# fill the lower triangle with the distances obtained elsewhere
dst[lower.tri(dst)] = x2$distance

# construct a phylogenetic tree with the neighbour-joining method
library(ape)
tr = nj(dst)
plot(tr)

树的 newick 格式可以用 ape::write.tree 函数保存或打印到控制台:

cat(write.tree(tr))
# (BGC53:0.196875,BGC45:0.153125,(((BGC35:0.025,BGC51:0.275):0.1583333333,BGC31:0.2416666667):0.240625,BGC34:0.246875):0.003125);