英文:
Projecting a function between two vectors, into a data frame in R
问题
在R中,可以使用energy
包中的dcor(X,Y)
函数来计算两个向量X
和Y
之间的距离系数。您有一个类似以下的矩阵Z
:
library(energy)
Z <- data.frame(Z1 = c(0.2, 3, 0.01, 3.4, 6),
Z2 = c(2.2, 3.5, 0.5, 0.3, 7.0),
Z3 = c(4.7, 0.003, 1.4, 0, 0.6))
您想要为所有可能的组合创建距离相关性矩阵。您可以创建一个函数来执行此计算。最终结果应该如下所示:
Z1 Z2 Z3
Z1 1 0.76 0.76
Z2 0.76 1 0.48
Z3 0.76 0.48 1
英文:
The distance coefficient in R
between two vectors X
,Y
can be calculated with the dcor(X,Y)
function of energy
package. I have a matrix Z
like this
library(energy)
Z <- data.frame(Z1 = c(0.2, 3, 0.01, 3.4, 6),
Z2 = c(2.2, 3.5, 0.5, 0.3, 7.0),
Z3 = c(4.7, 0.003, 1.4, 0, 0.6))
and I want to create the distance correlation matrix for all combinations. How can I create a function that does this calculation? The final result must look like this
Z1 Z2 Z3
Z1 1 0.76 0.76
Z2 0.76 1 0.48
Z3 0.76 0.48 1
答案1
得分: 3
似乎 energy::dcor
无法像 stats::cor
那样在单个数据框上执行交叉计算。一个解决方法是使用 outer
:
outer(Z, Z, Vectorize(energy::dcor))
# Z1 Z2 Z3
# Z1 1.0000000 0.7632896 0.7647835
# Z2 0.7632896 1.0000000 0.4783923
# Z3 0.7647835 0.4783923 1.0000000
英文:
I seems that energy::dcor
cannot do cross computation on a single dataframe like stats::cor
. A workaround is using outer
:
outer(Z, Z, Vectorize(energy::dcor))
# Z1 Z2 Z3
# Z1 1.0000000 0.7632896 0.7647835
# Z2 0.7632896 1.0000000 0.4783923
# Z3 0.7647835 0.4783923 1.0000000
答案2
得分: 2
我们可以使用 combn
来计算仅需要的成对组合,然后转换为 matrix
- 因此,我们不必重复相同的计算
library(energy)
v1 <- combn(Z, 2, FUN = \(x) dcor(x[[1]], x[[2]]))
as.matrix(as.dist(c(0, v1)))[-1, -1]
2 3 4
2 0.0000000 0.7632896 0.7647835
3 0.7632896 0.0000000 0.4783923
4 0.7647835 0.4783923 0.0000000
英文:
We may use combn
to calculate only needed pairwise combinations and then convert to matrix
- thus, we don't have to redo the same calculations
library(energy)
v1 <- combn(Z, 2, FUN = \(x) dcor(x[[1]], x[[2]]))
as.matrix(as.dist(c(0, v1)))[-1, -1]
2 3 4
2 0.0000000 0.7632896 0.7647835
3 0.7632896 0.0000000 0.4783923
4 0.7647835 0.4783923 0.0000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论