user3727200
user3727200

Reputation: 33

How to create a table in R to show my correlation matrix

I am new to R and I need help. I have created correlation matrix using the rcorr command. I would like to see this as a table so I can export it and email to my prof. The problem I am running into is this error message. I am at my wits end on how to fix it. I have tried data.frame command as well as write.table command.

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ""rcorr"" to a data.frame

Upvotes: 1

Views: 12796

Answers (2)

jtk
jtk

Reputation: 1

Use this code: df.rcx.p = as.data.frame(rcx$P)

The code as.data.frame coerces that table into a dataframe. Then when you save the file into a csv, just open it with Excel then you can save either as csv or Excel.

Upvotes: 0

Seth
Seth

Reputation: 4795

You might just look at the structure of the rcorr object. Ill create one with:

> rcx=rcorr(x)

then look at its stucture with:

> str(rcx)
List of 3
 $ r: num [1:10, 1:10] 1 0.0503 0.0309 0.0462 0.0719 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : NULL
 $ n: int [1:10, 1:10] 100 100 100 100 100 100 100 100 100 100 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : NULL
 $ P: num [1:10, 1:10] NA 0.619 0.76 0.648 0.477 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : NULL
 - attr(*, "class")= chr "rcorr"

So it is an object with 3 components, the first and last one can be made into sensible tables. I am not sure which one of these you want to print.

If you need them to be dataframes this will work

 df.rcx.r=data.frame(rcx$r)

or

 df.rcx.p=data.frame(rcx$P)

Then you can save these to a csv file with:

 write.csv(df.rcx.r,'correlationmatrix.csv')

Upvotes: 9

Related Questions