通过聚合数据框的列来计算相关性 [英] Calculate correlation by aggregating columns of data frame

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

问题描述

我有以下数据框:

y <- data.frame(group = letters[1:5], a = rnorm(5) , b = rnorm(5), c = rnorm(5), d = rnorm(5) )

如何获得一个数据框,它为我提供了每行 a、b 和 c、d 列之间的相关性?

How to get a data frame which gives me the correlation between columns a,b and c,d for each row?

类似:sapply(y, function(x) {cor(x[2:3],x[4:5])})

谢谢,

推荐答案

您可以使用 apply

> apply(y[,-1],1,function(x) cor(x[1:2],x[3:4]))
[1] -1 -1  1 -1 1

ddply(虽然这可能有点矫枉过正,如果两行具有相同的group,它将对a&b和c&d列进行相关那些行):

Or ddply (although this might be overkill, and if two rows have the same group it will do the correlation of columns a&b and c&d for both those rows):

> ddply(y,.(group),function(x) cor(c(x$a,x$b),c(x$c,x$d)))
  group V1
1     a -1
2     b -1
3     c  1
4     d -1
5     e  1

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

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