计算 R 中数据帧中列对的相关性 [英] Calculate Correlations of Pairs of Columns in a Data Frame in R

查看:15
本文介绍了计算 R 中数据帧中列对的相关性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

set.seed(1)
y <- data.frame(a1 = rnorm(5) , b1 = rnorm(5), c1 = rnorm(5),  a2 = rnorm(5), b2 = rnorm(5), c2 = rnorm(5))

我想获得列对的相关性:cor(a1,a2), cor(b1,b2), cor(c1,c2)

I would like to obtain the correlations of the pairs of columns: cor(a1,a2), cor(b1,b2), cor(c1,c2)

我尝试了以下操作,但 NA 显示为输出:

I tried the following but NA's appear as output:

apply(y,2,function(x) cor(x[1],x[3]))

我想得到等同于

cor(y[,1],y[,4])
cor(y[,2],y[,5])
cor(y[,3],y[,6])

在我的实际数据框中,我有更多的列对.

In my actual data frame, I have many more pairs of columns.

有什么想法吗?

感谢您的支持.

推荐答案

num.vars <- length(y)
var1 <- head(names(y), num.vars / 2)
var2 <- tail(names(y), num.vars / 2)
mapply(cor, y[var1], y[var2])
#         a1         b1         c1 
#  0.2491625 -0.5313192  0.5594564 

这篇关于计算 R 中数据帧中列对的相关性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆