Calculate correlation by aggregating columns of data frame

前端 未结 3 390
时光说笑
时光说笑 2021-01-15 11:19

I have the following data frame:

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

How to

3条回答
  •  星月不相逢
    2021-01-15 12:14

    You could use apply

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

    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
    

提交回复
热议问题