本文介绍了按行显示两个数据框之间的相关性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数据框,其中有5列,每列100行.

I have 2 data frames w/ 5 columns and 100 rows each.

id       price1      price2     price3     price4     price5
 1         11.22      25.33      66.47      53.76      77.42
 2         33.56      33.77      44.77      34.55      57.42
...

基本上,我想获得相应行的相关性

I would like to get the correlation of the corresponding rows, basically

for(i in 1:100){
cor(df1[i, 1:5], df2[i, 1:5])
}

,但不使用for循环.我假设有某种方式可以使用 plyr 来执行此操作,但似乎无法正确执行.有什么建议吗?

but without using a for-loop. I'm assuming there's someway to use plyr to do it but can't seem to get it right. Any suggestions?

推荐答案

根据您要的是快速的解决方案,还是可以使用

Depending on whether you want a cool or fast solution you can use either

diag(cor(t(df1), t(df2)))

这很酷,但却很浪费(因为它实际上计算了您实际上不需要的所有行之间的相关性,因此它们将被丢弃)或

which is cool but wasteful (because it actually computes correlations between all rows which you don't really need so they will be discarded) or

A <- as.matrix(df1)
B <- as.matrix(df2)
sapply(seq.int(dim(A)[1]), function(i) cor(A[i,], B[i,]))

仅执行您想要的操作,但要键入的内容要多一些.

which does only what you want but is a bit more to type.

这篇关于按行显示两个数据框之间的相关性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 23:12