How to build a Correlation Matrix in R splitted by categories?

I have a dataframe which has 4 variables - cur, price, volume and carat.

Except the cut everything is a numerical variable: I am able to get the correlation matrix for price, volume and carat. Here is the below code,

Jewels_Input_Data_2 <- subset(Jewels_Input_Data,select = c(price,Volume,carat))

#Correlation Plot to examine the relationships between price, volume, caret
library(corrplot)
CorMatrix <- cor(Jewels_Input_Data_2)

Plot

The above plot shows the correlation matrix for all ordered levels of cut. I would like to show it for each level of cut next to each other.

In other words, I would like to break CorMatrix by the categorical variable - Cut which has ordered levels.

Say for each cut level - I would like to see the matrix values and Ideally I would like to then plot it using corrplot()

Please help me with this.

Upvotes: 1

Views: 1101

Answers (1)

David Klotz
David Klotz

Reputation: 2431

Not really sure what "Jewels_Input_Data" is, but as a reproducible example:

library(dplyr)
library(purrr)
library(ggplot2)

diamonds %>% 
  mutate(volume = x*y*z) %>% 
  select(cut, price, volume, carat) %>% 
  split(.$cut) %>% 
  map(~ select(., -cut)) %>% 
  map(~ cor(.)) %>% 
  map(~ corrplot(., method = "number"))

Upvotes: 3

Related Questions