Search code examples
rdataframemelt

How to melt my dataframe in r


I have the below dataframe:

      num   type         f
1:      1     aa    0.8103
2:      1     ba    0.7500
3:      2     bb    0.8602
4:      3     bb    0.9017
5:      3     aa    0.6308
6:      3     cc    0.8491

I'd like to rearrange my data so that my columns will be "num", the rows will be "type" and the values will be "f" and if there is no "f", it will write "0", as below:

             1        2         3
aa      0.8103        0    0.6308
ba      0.7500        0         0
bb           0   0.8602    0.9017
cc           0        0    0.8491      

Anyone know how can I rearrange my dataframe?


Solution

  • library(tidyr)
    df %>% spread(num, f, fill=0)
    
     type      1      2      3
      1   aa 0.8103 0.0000 0.6308
      2   ba 0.7500 0.0000 0.0000
      3   bb 0.0000 0.8602 0.9017
      4   cc 0.0000 0.0000 0.8491