Question

I have this data

   RES  RANK1   RANK2   RANK3   RANK4   RANK5
    1   3   3   5   16  1
    2   3   1   2   5   16
    3   3   5   15  10  1

how do i melt the data such that values of RANK1 to RANK5 becomes the variable and RANK1 to RANK5 becomes the value.

The data were gathered by: among the list of (22) items, select the top 5 preferences.

The new data would be analyze as if the answers are multi response.

expected output would be (eg.RES=1)

RES 1      2      3        5       10       15     16
1   RANK5         RANK2    RANK3                   RANK4
2   RANK2  RANK3  RANK1    RANK4                   RANK5
3   RANK5         RANK1    RANK2   RANK4    RANK3

Thanks!

Was it helpful?

Solution

You will neeed to melt your data and then dcast it. Because you don't have unique values for each combination you need some way to keep all values when you have more than one (as happens here for RES == 1 and VALUE == 3). In this case we just concatenate the values using paste with a collapse argument:

dcast( melt( df , measure = 2:6 ) , RES ~ value , value.var = "variable" , fun = function(x) paste(x,collapse=";") , fill = ""   )
#  RES     1     2           3     5    10    15    16
#1   1 RANK5       RANK1;RANK2 RANK3             RANK4
#2   2 RANK2 RANK3       RANK1 RANK4             RANK5
#3   3 RANK5             RANK1 RANK2 RANK4 RANK3     

The effect of melt using the RANK* columns as measure variables is to give us a long dataset with two columns of id variables like so

head( melt( df , measure = 2:6 ) )
#  RES variable value
#1   1    RANK1     3
#2   2    RANK1     3
#3   3    RANK1     3
#4   1    RANK2     3
#5   2    RANK2     1
#6   3    RANK2     5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top