3

这是我第一次与 R 合作。

我有一张 3 列 12090 行(156 个细菌)的桌子。前两列是细菌的名称,最后一列是表示生物之间相关性的数字(基于一种基因组相似性)。例如(组成数字):

bacteria1    bacteria2    0.25846
bacteria1    bacteria3    0.35986
bacteria2    bacteria1    0.57896
bacteria2    bacteria3    0.54596
bacteria3    bacteria1    0.23659
bacteria3    bacteria2    0.36528

我希望能够将这些邻居加入到某种系统发育树中。我看到'nj'需要一个距离矩阵来做到这一点。我如何将其转换为距离矩阵或可用格式?(数字已经是距离,所以不应该做任何数学运算)我已经尝试过 as.dist() 和 as.matrix() 和 reshape() 但作为新手,我可能做错了一切。(重塑可能是我需要的..)

或者,如果有人知道如何通过其他方式将它们变成一棵树,那就太好了。

谢谢你的帮助。

4

2 回答 2

2

听起来您有距离矩阵的上三角部分或下三角部分,但没有尺寸。(虽然你确定你有 156 行吗?如果有 18 种细菌,应该有choose(18,2)= 153 个条目,而不是 156 个。)

假设您的表中确实有 153 行,您可以这样填写矩阵:

m <- matrix(nrow=18, ncol=18)
m[row(m) < col(m)] <- x         # if it's the upper triangular portion

或者

m[row(m) > col(m)] <- x         # if it's the lower triangular portion

然后diag(m) <- 0是对角线。

于 2012-10-12T00:20:12.953 回答
2

使用库reshape2(这与基础 R 中的 reshape 函数不同,而且我认为很多

# Load the library (after installing it, of course)
library(reshape2)

# Load up your data - for future reference, it's always helpful to post your data
# with a question.  I used dput(x) to generate this structure below:
x <- structure(list(V1 = structure(c(1L, 1L, 2L, 2L, 3L, 3L), 
     .Label = c("bacteria1", "bacteria2", "bacteria3"),
     class = "factor"), V2 = structure(c(2L, 3L, 1L, 3L, 1L, 2L),
     .Label = c("bacteria1", "bacteria2", "bacteria3"), class = "factor"),
     V3 = c(0.25846, 0.35986, 0.57896, 0.54596, 0.23659, 0.36528)),
     .Names = c("V1", "V2", "V3"), class = "data.frame",
     row.names = c(NA, -6L))

# Recast it - acast returns a matrix with V1 as the records, V2 as the columns,
# and V3 as the values
distmat <- acast(x, V1 ~ V2, value.var = "V3")
于 2012-10-11T21:30:54.880 回答