将属性向量转换为具有元素差异的矩阵 [英] Transform attribute vector into a matrix with differences of elements
问题描述
类似于此以前的帖子,我需要从属性向量转换成矩阵.这次是使用R的成对元素之间的差异.
Similarly to this previous post I need to transfrom an attribute vector into a matrix. This time with differences between pairs of elements using R.
例如,我有一个向量,该向量报告了N人的年龄(18至90岁).我需要将此向量转换为名为A的NxN矩阵(行和列上都有人的名字),其中每个单元格Aij的值均为| age_i-age_j |的值,代表两个人i和j之间年龄的绝对差异.
For example I have a vector which reports the age of N people (from 18 to 90 years). I need to convert this vector into a NxN matrix named A (with people names on rows and columns), where each cell Aij has the value of |age_i-age_j|, representing the absolute difference in age between the two people i and j.
这里有一个3个人的例子,第一人18岁,第二人23岁,第三人60岁,他们产生了这个向量:
Here is an example with 3 persons, first 18 yo, second 23 yo, third 60 yo, which produce this vector:
c(18, 23, 60)
我想将其转换为这个矩阵:
I want to transform it into this matrix:
A = matrix( c(0, 5, 42, 5, 0, 37, 42, 37, 0), nrow=3, ncol=3, byrow = TRUE)
推荐答案
tmp <- c(18, 23, 60)
您可以将dist
与两个参数一起使用:
You can use dist
with a couple of arguments:
dist(tmp, upper=TRUE, diag=TRUE)
1 2 3
1 0 5 42
2 5 0 37
3 42 37 0
请注意,dist
函数返回一个"dist"对象,因此您可能需要使用as.matrix
将其强制转换为矩阵.然后,您可以删除参数:
Note that the dist
function returns a "dist" object, so you might want to coerce it to a matrix with as.matrix
. Then you can drop the arguments:
as.matrix(dist(tmp))
1 2 3
1 0 5 42
2 5 0 37
3 42 37 0
或再次使用outer
.给它减去减法运算符,然后取绝对值.
Or again use outer
. Feed it the subtraction operator, then take the absolute value.
abs(outer(tmp, tmp, "-"))
[,1] [,2] [,3]
[1,] 0 5 42
[2,] 5 0 37
[3,] 42 37 0
推测dist
将比outer
快,因为该算法可以利用这种计算中存在的对称性,而outer
更通用.
Presumably, dist
will be faster than outer
, since the algorithm can take advantage of the symmetry that is present in such a calculation, while outer
is more general.
这篇关于将属性向量转换为具有元素差异的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!