2

I was trying to use the reshape-function to reshape a data.frame from wide to long format. I was following an example Reshaping wide to long with multiple values columns, but the correct answer seems not to work for me.

It seems that the problem is, that reshape only works, if the names of the columns are in alphabetical order. I rewrote the example a little bit, to explain the problem. As you can see, in the reformatted table, the values of the columns are switched. Values from "avg" are in "asd" and vice versa.

Is this a bug, or am I thinking wrong?

Greeting, Silke

    dw <- read.table(header=T, text='
 sbj f1.avg f1.asd f2.avg f2.asd  blabla
                 A   10    6     50     10      bA
                 B   12    5     70     11      bB
                 C   20    7     20     8       bC
                 D   22    8     22     9       bD
                 ')


reshape(dw, direction='long', 
        varying=c('f1.avg', 'f1.asd', 'f2.avg', 'f2.asd'), 
        timevar='var',
        times=c('f1', 'f2'),
        v.names=c('avg', 'asd'),
        idvar='sbj')
R learner
  • 101
  • 7

1 Answers1

3

The problem is how you're defining your varying variable: you're telling R that all 4 variables are actually one, but it needs to be 2 (avg and asd), as you're telling in v.names.
You have to define varying as a list of 2:

reshape(dw, 
        varying=list(c("f1.avg", "f2.avg"), c("f1.asd", "f2.asd")),
        timevar='var', direction="long", idvar="sbj", v.names=c("avg", "asd"), times=c("f1", "f2"))
#     sbj blabla var avg asd
#A.f1   A     bA  f1  10   6
#B.f1   B     bB  f1  12   5
#C.f1   C     bC  f1  20   7
#D.f1   D     bD  f1  22   8
#A.f2   A     bA  f2  50  10
#B.f2   B     bB  f2  70  11
#C.f2   C     bC  f2  20   8
#D.f2   D     bD  f2  22   9
Cath
  • 23,906
  • 5
  • 52
  • 86