Search code examples
rreshape2meltdcast

Need assistance in reshaping the data


I'm new here and also to R world. I have been trying to reshape the data but i couldn't do it after going through dcast, melt ,reshape options.

my data looks like, original data

TESTCODE BATCHNUMBER BATCHVALUE DATALINEID

test 1 100 _83281
test 1 99 _83284
test 1 100 _83287
test 1 101 _83290
test 2 101 _83281
test 2 95 _83284
test 2 99 _83287
test 2 98 _83290
test 3 99 _83281
test 3 103 _83284
test 3 102 _83287
test 3 100 _83290

and it needs to be transformed to something like this,

Desired output

TESTCODE DATALINEID BATCH1 BATCH2 BATCH3

 TEST     _83281       100      101       99
 TEST     _83284        99       95      103
 TEST     _83287       100       99      102
 TEST     _83290       101       98      100

i have tried using dcast(TEST,TESTCODE+DATALINEID ~., value.var = "BATCHVALUE") , which gives output like

TESTCODE   DATALINEID  .
 test     _83281      3
 test     _83284      3
 test     _83287      3
 test     _83290      3

and also dcast(TEST, TESTCODE+BATCHNUMBER ~ DATALINEID +., value.var = "BATCHVALUE")

TESTCODE BATCHNUMBER _83281 _83284 _83287 _83290

 test           1    100     99    100    101
 test           2    101     95     99     98
 test           3     99    103    102    100

Looking forward to the replies, thereby learning something new. Thank you.


Solution

  • I found the answer,

    dcast(data = TEST,formula =TESTCODE+DATALINEID~BATCHNUMBER, value.var="BATCHVALUE")

    The desired output,

    TESTCODE DATALINEID 1 2 3

    test     _83281    100    101     99
    test     _83284     99     95    103
    test     _83287    100     99    102
    test     _83290    101     98    100