Calculate correlation by aggregating columns of data frame

前端 未结 3 414
时光说笑
时光说笑 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条回答
  •  猫巷女王i
    2021-01-15 12:09

    You can use apply to apply a function to each row (or column) of a matrix, array or data.frame.

    apply(
      y[,-1], # Remove the first column, to ensure that u remains numeric
      1,      # Apply the function on each row
      function(u) cor( u[1:2], u[3:4] )
    )
    

    (With just 2 observations, the correlation can only be +1 or -1.)

提交回复
热议问题