0

I have a dataset as below:

SUBD | X1 | X2
0    |.789|.655
1    |.889|.998

I was trying to convert the above dataset in the below format:

SUBD  | WK  | Per
0     | X1  | .789
0     | X2  | .655
1     | X1  | .889
1     | X2  | .998

I have tried reshape, melt, cast, t, gather function available in R but not able to get the desired output? Can anyone help me to achieve this?

Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
srivakin
  • 1
  • 3

3 Answers3

3

I would use tidyr.

library(tidyr)
tmp <- read.delim(text = "SUBD | X1 | X2
0 |.789|.655
1 |.889|.998", sep = "|")
gather(tmp, WK, Per, -SUBD)

#SUBD WK   Per
#1    0 X1 0.789
#2    1 X1 0.889
#3    0 X2 0.655
#4    1 X2 0.998
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
1

When you use data.table the following give you exactly what you want.

TT <- melt.data.table(TT, id.vars="SUBD", variable.name="WK", value.name="Per")
TT[order(SUBD)]

First, convert your data into data.table. I created the table based on your example.

TT <- data.table(SUBD <- c(0, 1),
                 X1 <- c(.789, .889),
                 X2 <- c(.655, .998))
names(TT) <- c("SUBD", "X1", "X2")

Second, melt using melt.data.table. Lastly sort as shown. The result is what you intended.

   SUBD WK   Per
1:    0 X1 0.789
2:    0 X2 0.655
3:    1 X1 0.889
4:    1 X2 0.998

If you want to brush up on melt and cast operations, refer to this article here.

Sun Bee
  • 1,595
  • 15
  • 22
1

How about:

library("reshape")
df <- data.frame(SUBD = c(0,1), X1 = c(.789, .889), X2 = c(.655, .998))
reshape::melt(df, id = c("SUBD"))
Edgar Santos
  • 3,426
  • 2
  • 17
  • 29