daragh daragh - 3 months ago 14
R Question

Reshaping my data frame and adding a flag

I have a data frame that looks like this:

df <-
ID TIME IPREDP IPREDM
1 0.5 10 5
1 1.0 15 7
2 0.7 8 2


I want to reshape my data and collapse the
IPREDP
and
IPREDM
columns into one column called
IPRED
and add a flag called
DVID
for each and get rid of the original
IPREDP
and
IPREDM
columns. So the output should be this:

dfout <-
ID TIME DVID IPRED
1 0.5 1 10
1 0.5 2 5
1 1.0 1 15
1 1.0 2 7
2 0.7 1 8
2 0.7 2 2


How can I achieve this in R in the fastest possible way?

dww dww
Answer
library(reshape2)
dfout <- melt(df,measure=c("IPREDP","IPREDM"), value="IPRED", variable="DVID")
dfout$DVID <- as.integer(dfout$DVID)