0

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?

daragh
  • 173
  • 1
  • 11
  • With tidyr and dplyr, `df %>% gather(DVID, IPRED, IPREDP:IPREDM) %>% mutate(DVID = as.integer(factor(DVID, levels = c('IPREDP', 'IPREDM'))))` – alistaire Aug 09 '16 at 02:03
  • using library(reshape2), `melt(df,measure.vars =c("IPREDP","IPREDM"), value.name="IPRED")` – dww Aug 09 '16 at 02:08
  • In base R - `reshape(df, idvar=c("ID","TIME"), direction="long", varying=3:4, v.names="IPRED", timevar="DVID")` – thelatemail Aug 09 '16 at 02:20

3 Answers3

2
library(reshape2)
dfout <- melt(df,measure=c("IPREDP","IPREDM"), value="IPRED", variable="DVID")
dfout$DVID <- as.integer(dfout$DVID)
dww
  • 30,425
  • 5
  • 68
  • 111
2
   library("data.table") 
   df1 <- melt(df, id = c("ID", "TIME"), measure  = c("IPREDP", "IPREDM"), value.name = "IPRED")
   df1$DVID <- as.integer(df1$variable)
   df1[, variable := NULL]
Sathish
  • 12,453
  • 3
  • 41
  • 59
1

We can use melt from data.table

library(data.table)
melt(setDT(df), id.var = c("ID", "TIME"), value.name = "IPRED")[
          order(ID)][, DVID := 1:.N,.(ID, variable)][]
akrun
  • 874,273
  • 37
  • 540
  • 662