简体   繁体   中英

Difficulty with Long to Wide to Long Format in R

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM