user2261983
user2261983

Reputation: 75

Reshaping a data.frame in R

I got a temperature dataframe: I took temperature in Celsius every hour for evey single day, so I got a csv file like this:

   Day     Hour Temperature
11/10/2013  9:00    6
11/10/2013  10:00   11
11/10/2013  11:00   13
11/10/2013  12:00   6
11/10/2013  13:00   8
12/10/2013  9:00    7
12/10/2013  10:00   8
12/10/2013  11:00   11
12/10/2013  12:00   18
12/10/2013  13:00   12
13/10/2013  9:00    15
13/10/2013  10:00   8
13/10/2013  11:00   11
13/10/2013  12:00   16
13/10/2013  13:00   9

I'm trying to reorder it in R in order to get a record per day changing the header text:

  Day       9:00   10:00 11:00 12:00 13:00
11/10/2013    6      11    13    6     8
12/10/2013    7       8    11   18    12
13/10/2013   15       8    11   16     9

I tried several combinations of cbind, sapply and unique but I have no idea if they are the right R elements to reorder my data.frame. Any idea, suggestion? Many thanks

Upvotes: 2

Views: 131

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121057

Here's your data as a data frame.

temperatures <- read.table(
  text = "   Day     Hour Temperature
  11/10/2013  9:00    6
  11/10/2013  10:00   11
  11/10/2013  11:00   13
  11/10/2013  12:00   6
  11/10/2013  13:00   8
  12/10/2013  9:00    7
  12/10/2013  10:00   8
  12/10/2013  11:00   11
  12/10/2013  12:00   18
  12/10/2013  13:00   12
  13/10/2013  9:00    15
  13/10/2013  10:00   8
  13/10/2013  11:00   11
  13/10/2013  12:00   16
  13/10/2013  13:00   9",
  header = TRUE
)

Here's the solution suggested by Roland, using dcast.

library(reshape2)
dcast(temperatures, Day ~ Hour, value.var = "Temperature")

FYI, you are "reshaping" the data, not "reordering" it (which implies changing the row order but leaving the columns the same; use sort or plyr::arrange for that).


Using base R:

reshape(
  temperatures, 
  direction = "wide", 
  idvar     = "Day", 
  timevar   = "Hour", 
  v.names   = "Temperature"
)

Upvotes: 2

Related Questions