在R中,将两个向量之间的函数映射到数据框中可以这样实现:

huangapple go评论68阅读模式
英文:

Projecting a function between two vectors, into a data frame in R

问题

在R中,可以使用energy包中的dcor(X,Y)函数来计算两个向量XY之间的距离系数。您有一个类似以下的矩阵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 &lt;- 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 &lt;- 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

huangapple
  • 本文由 发表于 2023年2月18日 18:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定