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

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

问题描述

我有以下数据框:

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

如何获取一个数据框,给出每行a,b和c列之间的相关性?

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])})

谢谢,
S

Thank you, S

推荐答案

您可以使用 apply

You could use apply

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

ddply (虽然这可能是过度的,两行具有相同的,它们将对这两行执行列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天全站免登陆