[英]dist() function in R outputs
I am curious about dist() output results that I get. 我很好奇我得到的dist()输出结果。 More specifically, if I try
更具体地说,如果我尝试
a=matrix(rnorm(1:100),nrow=10)
dist(a)
ok, I get what I expected 好的,我得到了我的预期
1 2 3 4 5 6 7 8 9
2 3.700582
3 3.793826 4.391523
4 3.063703 5.386797 5.494179
5 3.205545 4.464493 3.839944 3.763671
6 3.868796 4.954696 3.340530 5.165389 3.589912
7 3.906698 3.971069 3.405455 5.403859 4.284414 4.774963
8 2.620238 4.479064 5.403749 3.128820 4.237437 5.272889 5.551908
9 3.645784 4.586749 5.508289 3.333739 4.318391 6.113694 4.796519 3.641355
10 2.292591 4.152536 4.869231 3.445773 3.557222 3.992109 4.061925 3.740496 4.225799
Nice, but: when I have a larger matrix 很好,但是:当我有一个更大的矩阵
dim(Large_m)
[1] 978 235
I try 我试试
a=dist(Large_m)
I do not get a matrix, rather a 'Large dist' object as Rstudio says. Rstudio说,我没有得到矩阵,而是一个“大型”对象。
Is it correct if I use it with as.matrix
? 如果我和
as.matrix
一起使用它是否正确?
b=as.matrix(a)
b as I checked is indeed a matrix and seems like the distance matrix. b我检查确实是一个矩阵,看起来像距离矩阵。
Also, I really need the row names in the distance matrix, not just numbers but in this way (working with as.matrix
) I can't get it. 另外,我真的需要距离矩阵中的行名,而不仅仅是数字,但这样(使用
as.matrix
)我无法得到它。
Seems I'm missing something, can't be so complicated to just create a distance matrix in R. 似乎我错过了一些东西,不能在R中创建一个距离矩阵那么复杂。
Here's an explicit example of what was suggested in the comments by @ColonelBeauvel. 这是@ColonelBeauvel在评论中建议的一个明确的例子。 (I think there was some confusion due to a typo in a comment: as.matrix() vs is.matrix()...)
(我认为由于评论中的拼写错误导致了一些混乱:as.matrix()vs is.matrix()...)
Large random matrix: 大随机矩阵:
cols <- 325
rows <- 978
m <- matrix(rnorm(1:(rows*cols)), ncol=cols)
Let's give rows and columns a name: 让我们给行和列命名:
rownames(m) <- paste0("r", 1:rows)
colnames(m) <- paste0("c", 1:cols)
Calculate distance object with dist
then turn it into a regular matrix with as.matrix
(as suggested by Colonel Beauvel): 使用
dist
计算距离对象,然后将其转换为带有as.matrix
的常规矩阵(由Beauvel上校建议):
d <- dist(m)
dm <- as.matrix(d)
Check the types: 检查类型:
class(d)
[1] "dist"
class(dm)
[1] "matrix"
Names are preserved in the distance matrix dm. 名称保存在距离矩阵dm中。 Here's a small piece of it:
这是它的一小部分:
dm[1:3,1:3]
r1 r2 r3
r1 0.00000 24.64059 26.63301
r2 24.64059 0.00000 25.69792
r3 26.63301 25.69792 0.00000
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.