1

I am trying to make a graph similar to a correlation plot. However, my data was in long format and I wanted to only show the lower triangle of the matrix. Therefore, I took my data and reshaped it using the following:

x<-c('A','B','C')
data<-expand.grid(x,x)
data$value<-c(1,2,3,2,1,4,3,4,1)
r.data<-reshape(data, idvar = "Var1", timevar = "Var2", direction = "wide")
colnames(r.data)<-c('Var','A','B','C')
rownames(r.data)<-r.data$Var
r.data$Var<-NULL

Next I found the lower triangle portion of my data:

get_lower_tri<-function(cormat){
  cormat[upper.tri(cormat)] <- NA
  return(cormat)
}
r.data_lower<-get_lower_tri(r.data)

But when I use melt() I now only have one column for variable and values because there is no id. How would I define an id variable or fix something such that it would be in a standard melted format?

Expected:

Var1  Var2   value
 A     A       1
 B     A       2
 B     B       1
 C     A       3
 C     B       4
 C     C       1
Jack Armstrong
  • 1,182
  • 4
  • 26
  • 59

1 Answers1

1

An option is to convert to matrix and then melt with the na.rm = TRUE option

library(reshape2)
melt(as.matrix(r.data_lower), na.rm = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662