0

In R, is it possible to find multiple correlation matrix?

Any package/in-built function available?

Is it possible to specify order of correlations in cor()?

Kavipriya
  • 441
  • 4
  • 17
  • @Richard Scriven can you specify the how to add order in cor() in r? and how to find multiple correlation? – Kavipriya Jul 30 '15 at 05:17

1 Answers1

3

The base R function cor() produces a multiple correlation matrix.

The order of variables in its output will mimic their order in the data frame to which you apply it, so arrange your data frame, then apply cor(). Here's an example using piping in dplyr so you don't actually modify the stored data frame:

df <- data.frame(x = seq(10), y = rev(seq(10)), z = seq(10))
df %>%
    select(z, y, x) %>% # Use select() to reorder variables in df
    cor(.)

Result:

   z  y  x
z  1 -1  1
y -1  1 -1
x  1 -1  1
ulfelder
  • 5,305
  • 1
  • 22
  • 40
  • 4
    Is `dplyr` really necessary here? Can't we just `cor(df)`? Or `cor(df[c("z", "y", "x")])` if you wish? – David Arenburg Jul 29 '15 at 12:41
  • No, not necessary, just where my head went. Your second option does the same with less fuss. – ulfelder Jul 29 '15 at 12:42
  • It's Ok, in general this is a nice and compact solution. – David Arenburg Jul 29 '15 at 13:25
  • isn't it single correlation function if I am not wrong? – Kavipriya Jul 30 '15 at 04:24
  • @ulfelder cor() function produces zero order correlation, i.e., z on z, z on y, z on x, y on z, y on y, etc. But I want first order correlation, z on x&y, y on z&x and x on z&y combined. is that possible? – Kavipriya Jul 30 '15 at 04:30
  • I don't know of such a statistic. The package `ppcor` offers `pcor.test()` to consider the partial correlation of two variables, controlling for a third (e.g., x and y, conditional on z). To consider x on y + z, though, I think you'd need to run a regression. – ulfelder Jul 30 '15 at 09:12