Search code examples
rdataframecorrelation

how to get correlation between columns in a data frame or matrix in R


I have a data frame including 8 columns from X1 to X8. I want to get correlation between X2-X8 and X1 separately, for example X2 and X1, X3 and X1 .... X8 and X1 and finally getting 7 slopes.

set.seed(666)
g <- runif(96,1,5)
f <- matrix(g, ncol=8, nrow=12)
F <- data.frame(f)

Solution

  • Maybe separate into two parts directly as follows:

    set.seed(666)
    g <- runif(96,1,5)
    f <- matrix(g, ncol=8, nrow=12)
    F <- data.frame(f)
    cor(F[, 1], F[, -1])
    #>             X2         X3         X4         X5         X6         X7        X8
    #> [1,] -0.231461 -0.1484853 -0.4694454 -0.1203586 -0.3976857 -0.5073719 0.2560319
    

    Created on 2023-08-01 with reprex v2.0.2