lettucehead
lettucehead

Reputation: 19

R: reshape(..., direction = "long") changes index #'s. Why?

I think the numbers all the way on the left, here, could be called indices:

> read.csv(dir()[90]) -> hw1PL
> hw1PL
   Snum Gender Condition pref1 pref2 pref3 pref4 pref5 pref6
1     1      1         0     3     2     4     3     5     3
2     2      1         0     4     4     3     4     5     5
3     3      1         0     2     3     2     3     3     2
4     4      1         0     3     2     3     4     2     4

They parallel the Snum variable. But check this out:

> reshape(hw1PL, idvar = "Snum", varying = list(4:9), direction = "long") -> 
hw1PP
> hw1PP
     Snum Gender Condition time pref1
1.1     1      1         0    1     3
2.1     2      1         0    1     4
3.1     3      1         0    1     2
4.1     4      1         0    1     3

What's up? No explanation at all in the ?reshape file. I'd like to get pref1 renamed within the reshape() call as well, if possible. It seems unclean.

What's more, even worse, is reshaping back. Look at this hideous morass:

> reshape(hw1PP, idvar = "Snum", v.names = "pref1", direction = "wide")
     Snum Gender Condition pref1.1 pref1.2 pref1.3 pref1.4 pref1.5 pref1.6
1.1     1      1         0       3       2       4       3       5       3
2.1     2      1         0       4       4       3       4       5       5
3.1     3      1         0       2       3       2       3       3       2
4.1     4      1         0       3       2       3       4       2       4

Why in the world have those index values copulated on to the pref1's? Nothing is safe -- the longer I live with reshape(), the longer I live in fear of losing computational crispness to the phantom decimal it creates. This is like the ghosts generated from tearing the fabric between universes in The Subtle Knife (His Dark Materials vol. 2). Relevance: Changing one's dimension is inevitably problematic.

Upvotes: 0

Views: 65

Answers (1)

mnel
mnel

Reputation: 115390

If you specify v.names in your call to reshape(..., direction = 'long'), then all is good

reshape(hw1PL, idvar = "Snum", varying = list(4:9),  direction = "long",v.names='pref') -> hw1PP
head(hw1PP)
#     Snum Gender Condition time pref
# 1.1    1      1         0    1    3
# 2.1    2      1         0    1    4
# 3.1    3      1         0    1    2
# 4.1    4      1         0    1    3
# 1.2    1      1         0    2    2
# 2.2    2      1         0    2    4

And back we go.

reshape(hw1PP, idvar = "Snum", v.names = "pref", direction = "wide",sep='')
#     Snum Gender Condition pref1 pref2 pref3 pref4 pref5 pref6
# 1.1    1      1         0     3     2     4     3     5     3
# 2.1    2      1         0     4     4     3     4     5     5
# 3.1    3      1         0     2     3     2     3     3     2
# 4.1    4      1         0     3     2     3     4     2     4

Upvotes: 2

Related Questions