val val - 4 years ago 85
R Question

in R, reshaping a "mixed" data frame using melt and cast

I would like to plot two types of values against each other (dupl and orig). Is it possible to easily reshape the following data frame

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


to look like this?

record v1.orig v2.orig v3.orig v1.dupl v2.dupl v3.dupl
r1 0 0 1 0 0 1
r2 0 1 0
r3 0 0 0 0 0 0


The point being so that I can make a plot of vX.orig vs vX.dupl. Or is there a better way to do this?
I am looking at dcast() but can't seem to get what I want, possibly because my data is only partially molten (along type?).

EDIT: here is what I've tried:

df1<-melt(df,id="record")
dcast(df1,record~value, margins=TRUE)

Answer Source

you could do it like this:

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

or my original answer:

library(tidyverse)
df %>% gather(vx, num, -record, -type) %>%
    unite(type, vx, type) %>%
    spread(type, num)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download