0

Any ideas on how I should transpose or reshape my data frame from this:

    value               L2
1   2008-09-01T07:00:00 timestamp
2   621.31              ht
3   0                   X3
4   2008-09-02T07:00:00 timestamp
5   621.24              ht
6   0                   X3
7   2008-09-03T07:00:00 timestamp
8   621.25  ht
9   0                   X3

To this:

    timestamp           ht      X3
1   2008-09-01T07:00:00 621.31  0
2   2008-09-02T07:00:00 621.24  0
3   2008-09-03T07:00:00 621.25  0

I'm trying to change the 2nd column into column names and keeping the timestamp and ht records paired.

*The title needs some work, if someone has a better idea I'd be happy to try and change it.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
dave_h
  • 15
  • 4

1 Answers1

2

A simple unstack in base R will do the trick:

unstack(df)

      ht           timestamp X3
1 621.31 2008-09-01T07:00:00  0
2 621.24 2008-09-02T07:00:00  0
3 621.25 2008-09-03T07:00:00  0

This function is great to turn a two column data.frame where one column is values and the other names the variables into a wide data.frame of the appropriate shape.

data

df <- read.table(header=TRUE, text="    value               L2
1   2008-09-01T07:00:00 timestamp
2   621.31              ht
3   0                   X3
4   2008-09-02T07:00:00 timestamp
5   621.24              ht
6   0                   X3
7   2008-09-03T07:00:00 timestamp
8   621.25  ht
9   0                   X3")
lmo
  • 37,904
  • 9
  • 56
  • 69