0
votes

Using the built-in R data set mtcars, I would like to create a correlation table between selected variables in the data frame i.e. mpg and disp, mpg and hp, mpg and wt, disp and hp, disp and wt, hp and wt. I also want the table to display the p values.

                   mpg disp  hp drat    wt  qsec
Mazda RX4         21.0  160 110 3.90 2.620 16.46
Mazda RX4 Wag     21.0  160 110 3.90 2.875 17.02
Datsun 710        22.8  108  93 3.85 2.320 18.61
Hornet 4 Drive    21.4  258 110 3.08 3.215 19.44
Hornet Sportabout 18.7  360 175 3.15 3.440 17.02
Valiant           18.1  225 105 2.76 3.460 20.22
1
So can you please post an expected output format? - AnilGoyal
@AnilGoyal Two tables with the columns and rows as the variables, one table showing the correlation coefficient and the second table showing the p values - james

1 Answers

1
votes

You can use Hmisc package like

library(Hmisc)

#Create the data
df <- subset(mtcars, select = c("mpg", "disp",  "hp", "drat", "wt", "qsec"))

#Calculate correlation using base R
round(cor(df),2)

#Calculate correlation using Hmisc package
rcorr(as.matrix(df), type=c("pearson"))