在R中,重塑a";混合;使用熔化和浇铸的数据帧
我想绘制两种类型的值(dupl和orig)。是否可以轻松重塑以下数据帧在R中,重塑a";混合;使用熔化和浇铸的数据帧,r,casting,scatter-plot,melt,R,Casting,Scatter Plot,Melt,我想绘制两种类型的值(dupl和orig)。是否可以轻松重塑以下数据帧 record=c("r1","r1","r2","r3","r3") v1=rep(0,5) v2=c(0,0,1,0,0) v3=c(1,1,0,1,1) type=c("orig","dupl","orig","orig","dupl") df<-data.frame(record, v1, v2, v3, type) df record v1 v2 v3 type 1 r1 0 0 1 ori
record=c("r1","r1","r2","r3","r3")
v1=rep(0,5)
v2=c(0,0,1,0,0)
v3=c(1,1,0,1,1)
type=c("orig","dupl","orig","orig","dupl")
df<-data.frame(record, v1, v2, v3, type)
df
record v1 v2 v3 type
1 r1 0 0 1 orig
2 r1 0 0 1 dupl
3 r2 0 1 0 orig
4 r3 0 0 1 orig
5 r3 0 0 1 dupl
重点是我可以画出vX.orig和vX.dupl的图。还是有更好的方法?
我正在查看dcast(),但似乎无法得到我想要的,可能是因为我的数据只是部分熔化(沿类型?)
编辑:以下是我尝试过的:
df1<-melt(df,id="record")
dcast(df1,record~value, margins=TRUE)
df1您可以这样做:
library(reshape2)
melted <- melt(df, id.vars= c("record", "type"))
dcast(melted, record ~ variable + type)
record v1_dupl v1_orig v2_dupl v2_orig v3_dupl v3_orig
1 r1 0 0 0 0 1 1
2 r2 NA 0 NA 1 NA 0
3 r3 0 0 0 0 1 1
在base R中,这是一个简单的重塑:
reshape(df, idvar="record", timevar="type", direction="wide")
# record v1.orig v2.orig v3.orig v1.dupl v2.dupl v3.dupl
#1 r1 0 0 1 0 0 1
#3 r2 0 1 0 NA NA NA
#4 r3 0 0 1 0 0 1
这里是另一个使用recast
从restrape2
library(reshape2)
recast(df, record~variable + type)
# record v1_dupl v1_orig v2_dupl v2_orig v3_dupl v3_orig
#1 r1 0 0 0 0 1 1
#2 r2 NA 0 NA 1 NA 0
#3 r3 0 0 0 0 1 1
这是否可以推广到不以“v”开头的列。。。在我的真实场景中,我希望我的所有列(40)都复制为“_dupl”。如果您可以将该部分调整为其他dplyr::select()
terms,请使用restrape2
reshape(df, idvar="record", timevar="type", direction="wide")
# record v1.orig v2.orig v3.orig v1.dupl v2.dupl v3.dupl
#1 r1 0 0 1 0 0 1
#3 r2 0 1 0 NA NA NA
#4 r3 0 0 1 0 0 1
library(reshape2)
recast(df, record~variable + type)
# record v1_dupl v1_orig v2_dupl v2_orig v3_dupl v3_orig
#1 r1 0 0 0 0 1 1
#2 r2 NA 0 NA 1 NA 0
#3 r3 0 0 0 0 1 1