简体   繁体   English

R 中的 Long 到 Wide 到 Long 格式的困难

[英]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.但是当我使用melt()我现在只有一列变量和值,因为没有id。 How would I define an id variable or fix something such that it would be in a standard melted format?我将如何定义 id 变量或修复某些内容,使其采用标准的融合格式?

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一个选项是转换为matrix ,然后用na.rm = TRUE选项melt

library(reshape2)
melt(as.matrix(r.data_lower), na.rm = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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