Calculate correlation by aggregating columns of data frame

前端 未结 3 389
时光说笑
时光说笑 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:07

    You're almost there: you just need to use apply instead of sapply, and remove unnecessary columns.

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

    Of course, the correlation between two length-2 vectors isn't very informative....

提交回复
热议问题