Reshaping data in R using melt

296 views Asked by At

I have tried to apply what people have suggested to reshape data, but somehow I am failing to get my data reshaped like I want it. I would really appreciate it if someone can help:

My data looks like this:
      AB      LP     PD1     PD2     PY1     PY2     PY3     PY4     PY5 t
1 -50.000 -50.000 -50.000 -50.000 -50.000 -50.000 -50.000 -50.000 -50.000 1
2 -50.153 -53.316 -50.416 -50.416 -53.455 -53.467 -53.700 -53.403 -53.218 2
3 -50.288 -54.399 -50.726 -50.726 -53.603 -53.644 -54.457 -53.664 -53.776 3
4 -50.410 -53.630 -50.956 -50.956 -52.385 -52.649 -53.642 -52.575 -52.740 4
5 -50.519 -53.075 -51.127 -51.127 -52.072 -52.174 -53.132 -51.715 -52.563 5
6 -50.617 -52.616 -51.255 -51.255 -52.023 -51.947 -52.602 -51.857 -52.643 6
>

and I want to change it so that I can plot it with ggplot which need it like this:

AB -50.000 1
AB -50.153 2
AB -50.288 3

etc, where the third columns is the last column from the original data, which is time (column t)

If I use v=melt(values) I get this:

      variable   value
1       AB -50.000
2       AB -50.153
3       AB -50.288
4       AB -50.410
5       AB -50.519
6       AB -50.617

which is almost there, but now the time column (t) is added at the bottom. How do I get time to be third column?

I believe this is the format I need the data to be in to plot multiple lines using ggplot2.

Thanks for any help

JSS

1

There are 1 answers

2
Nick Kennedy On BEST ANSWER

Using reshape2, you need to do:

v <- melt(values, id.vars = "t")