2016-03-28 14 views
0

Ich habe eine Datenmenge, die wie folgt aussieht:Programm zu schwenken Daten in R

item  01/02/2016 01/03/2016 01/04/2016 
-------  --------- --------- ---------- 
juice   0   0   4 
cola   1   3   6 
bananas  5   9   1 

Ich möchte die Daten so verschwenken, dass das Endergebnis sieht wie folgt aus:

item date    amount 
------- -----   ------ 
juice 01/02/2016  0 
juice 01/03/2016  0 
juice 01/04/2016  4 
cola 01/02/2016  1 
cola 01/03/2016  3 
cola 01/04/2016  6 
bananas 01/02/2016  5 
bananas 01/03/2016  9 
bananas 01/04/2016  1 

Ich habe es in Excel gemacht, aber ich würde gerne ein Programm schreiben, um es in R zu automatisieren. Wie würde ich darüber gehen?

Danke!

+0

Blick auf 'melt' von„reshape2“oder„data.table“, oder Sieh dir 'great' von" tidyr "an. – A5C1D2H2I1M1N2O1R2T1

+0

In der Basis R sollte eine Kombination aus 'stack' und' cbind' genügen. – A5C1D2H2I1M1N2O1R2T1

Antwort

1

Versuchen Sie dies, aber der Variablenname kann nicht ein Datum sein, so neu zuordnen die Variablennamen an die Tage nach dem Umformen:

> df 
     item d01 d02 d03 
    1 juice 0 0 4 
    2 cola 1 3 6 
    3 bananas 5 9 1 
    > library(reshape2) 
    > df2 <- melt(df, id.vars=1) 
    > df2 
     item variable value 
    1 juice  d01  0 
    2 cola  d01  1 
    3 bananas  d01  5 
    4 juice  d02  0 
    5 cola  d02  3 
    6 bananas  d02  9 
    7 juice  d03  4 
    8 cola  d03  6 
    9 bananas  d03  1 
    > df2[order(df2$item),] 
     item variable value 
    3 bananas  d01  5 
    6 bananas  d02  9 
    9 bananas  d03  1 
    2 cola  d01  1 
    5 cola  d02  3 
    8 cola  d03  6 
    1 juice  d01  0 
    4 juice  d02  0 
    7 juice  d03  4