r - 计算两个数据帧之间的相关性是否需要循环?

标签 r dataframe correlation

我有一组看起来像 A 和 B 的大型数据框:

A <- data.frame(A1=c(1,2,3,4,5),B1=c(6,7,8,9,10),C1=c(11,12,13,14,15 ))

  A1 B1 C1
1  1  6 11
2  2  7 12
3  3  8 13
4  4  9 14
5  5 10 15

B <- data.frame(A2=c(6,7,7,10,11),B2=c(2,1,3,8,11),C2=c(1,5,16,7,8))

  A2 B2 C2
1  6  2  1
2  7  1  5
3  7  3 16
4 10  8  7
5 11 11  8

我想创建一个向量 (C),表示 A1 和 A2、B1 和 B2 以及 C1 和 C2 之间的皮尔逊相关性。例如,在这种情况下,这些相关性是:
[1] 0.95 0.92 0.46

最佳答案

cor接受两个 data.frames:

A<-data.frame(A1=c(1,2,3,4,5),B1=c(6,7,8,9,10),C1=c(11,12,13,14,15 ))

B<-data.frame(A2=c(6,7,7,10,11),B2=c(2,1,3,8,11),C2=c(1,5,16,7,8))

cor(A,B)

#           A2        B2       C2
# A1 0.9481224 0.9190183 0.459588
# B1 0.9481224 0.9190183 0.459588
# C1 0.9481224 0.9190183 0.459588

diag(cor(A,B))
#[1] 0.9481224 0.9190183 0.4595880

编辑:

以下是一些基准:
Unit: microseconds
                   expr     min       lq   median       uq      max neval
        diag(cor(A, B)) 230.292 238.4225 243.0115 255.0295  352.955   100
      mapply(cor, A, B) 267.076 281.5120 286.8030 299.5260  375.087   100
 unlist(Map(cor, A, B)) 250.053 259.1045 264.5635 275.9035 1146.140   100

编辑 2:

和一些更好的基准使用
set.seed(42)
A <- as.data.frame(matrix(rnorm(10*n),ncol=n))
B <- as.data.frame(matrix(rnorm(10*n),ncol=n))

enter image description here

但是,我可能应该提到这些基准测试在很大程度上取决于行数。

编辑 3:因为我被要求提供基准测试代码,所以在这里。
b <- sapply(2^(1:12), function(n) {
    set.seed(42)
    A <- as.data.frame(matrix(rnorm(10*n),ncol=n))
    B <- as.data.frame(matrix(rnorm(10*n),ncol=n))

    require(microbenchmark)
    res <- print(microbenchmark(
                   diag(cor(A,B)),
                   mapply(cor, A, B),
                   unlist(Map(cor,A,B)),
                   times=10
                 ),unit="us")
    res$median
})

b <- t(b)

matplot(x=1:12,log10(b),type="l",
        ylab="log10(median [µs])", 
        xlab="log2(n)",col=1:3,lty=1)
legend("topleft", legend=c("diag(cor(A, B))", 
                           "mapply(cor, A, B)",
                           "unlist(Map(cor,A,B))"),lty=1, col=1:3)

关于r - 计算两个数据帧之间的相关性是否需要循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535231/

相关文章:

python - 如何将相关热图限制为有趣的单元格并添加星号以标记异常值?

python - 如何在 Pandas 数据框中用不同颜色为 bool 值着色

r - r 中四个变量的折线图在一张图中

r - ls() 和 objects() 的区别

r - 如何在 ggplot2 中标记 geom_dotplot 的点?

python - 累积总和但有条件地排除较早的行

Python 数据帧 : Merge values of columns according to a specific condition

Matlab:相关数

python - Python 中的内核关联

r - ggplot2 图表轴中的印度风格千位分隔符