rreshapereshape2long-format-data

reshape function not mapping values correctly


I am working with a within-subjects design looking at how participants rated 20 videos across a variety of variables (valence, arousal, etc.) and am trying to turn my wide-format df into a long format so it looks like this...

ID Video_Type Valence Arousal
123 Comedy 1 100
123 Drama 4 82

Currently the wide-format looks something like this:

ID Comedy.valence Comedy.arousal Comedy.rating Drama.valence Drama.arousal
111 1 1 100 5 7
999 6 4 82 3 8

When I use the code below all of the column names for the long dataset are correct but the values aren't mapping on correctly (e.g., the values for valence are placed under arousal, the values for arousal are placed under rating, etc.)

reshape(videoratings, direction = "long", 
        varying=c(1:23), 
        timevar = "video",
        times = c("Comedy", "Drama", "Action"),
        v.names = c("valence", "arousal", "rating"),
        idvar = "ResponseId")

Does anyone know how to fix this?


Solution

  • Just need to switch the names. This cannot be reversed using the split = parameter hence use sub function

    reshape(setNames(df, sub("(\\w+).(\\w+)","\\2.\\1", names(df))), -1, dir='long', idv = 'ID')
    
                ID   time valence arousal rating
    111.Comedy 111 Comedy       1       1    100
    999.Comedy 999 Comedy       6       4     82
    111.Drama  111  Drama       5       7     20
    999.Drama  999  Drama       3       8     80