Jeff Boggs
Jeff Boggs

Reputation: 55

How do I print out a correlation matrix produced using basic R's cor(data) command?

Is there a simple way to just print out or export the correlation matrix from a cor() in basic R?

I can find ways to use pairs() and corrplot() to make very fancy representations of correlation matrices. However, I just want a basic table using the minimum amount of code so I can send it to my colleagues while I conduct exploratory data analysis. Currently I'm reduced to just copying and pasting, which has some problems when the number of variables gets too large. Here is the code I am using:

cor(survey.numeric,
    method = "pearson",
    use = "pairwise.complete.obs"
  )

...which then shows this in the Console:

          [,1]        [,2]        [,3]        [,4]         [,5]        [,6]
[1,]  1.000000000  0.02025609 -0.03283923  0.01175631 -0.008147165  0.02152592
[2,]  0.020256087  1.00000000 -0.06800116 -0.01759725  0.268759246  0.27833669
[3,] -0.032839232 -0.06800116  1.00000000 -0.58949678 -0.190928460 -0.02274723
[4,]  0.011756306 -0.01759725 -0.58949678  1.00000000  0.339508966  0.01340679
[5,] -0.008147165  0.26875925 -0.19092846  0.33950897  1.000000000  0.51178423
[6,]  0.021525920  0.27833669 -0.02274723  0.01340679  0.511784234  1.00000000

While I can cut and paste this, I can't help but think I am missing something. Is there a generic command that lets me create this output as an object (perhaps a table in .csv format, or just a .jpg) that then is passed to the plot screen? Something like this?

x <- cor(survey.numeric,
        method = "pearson",
        use = "pairwise.complete.obs"
      )
print(x)

where print(x) is the command I don't know. Optimally it would have some formatting options, too. I know how to print out a correlation matrix in corrplot(), but I'm looking for something very basic.

Thank you in advance.

Upvotes: 1

Views: 1356

Answers (1)

akrun
akrun

Reputation: 887128

We can use write.csv

write.csv(x, 'yourfile.csv')

Or instead of print, use cat with file option

cat(x, file = 'yourfile.txt')

Upvotes: 3

Related Questions