3

Possible Duplicate:
Reshape data from long to wide format R

With:

day <- c(1, 1, 2, 2)
prod <- c(1, 2, 1, 2)
cost <- c(20.1, 17.7, 15.2, 23.3)
record <- data.frame(day=day, prod=prod, cost=cost)

record
  day prod cost
1   1    1 20.1
2   1    2 17.7
3   2    1 15.2
4   2    2 23.3

What is a good (quick) way to reshape the data as:

       day_1 day_2
prod_1  20.1  15.2
prod_2  17.7  23.3

Thanks!

Community
  • 1
  • 1
Rock
  • 2,827
  • 8
  • 35
  • 47
  • Sorry about the duplicate as I didn't find the right word to search for similar questions. Thank you all for answering! – Rock Aug 10 '12 at 19:30

3 Answers3

6

We can also use xtabs

xtabs(cost ~ prod + day, data = record)

    day
prod    1    2
   1 20.1 15.2
   2 17.7 23.3
dickoa
  • 18,217
  • 3
  • 36
  • 50
4

Why not use tapply - the sum function doesn't matter as you have unique values:

> tapply(record$cost,list(record$prod, record$day), FUN=sum)

     1    2
1 20.1 15.2
2 17.7 23.3
Ina
  • 4,400
  • 6
  • 30
  • 44
  • This may not work as in a particular day there may be some product missing, but works excellently other than that. Thanks! – Rock Aug 10 '12 at 19:21
  • 1
    Should work fine, you'll just end up with `NA` in the cell where you have a missing data. Which seems like a good behaviour to me. – Ina Aug 10 '12 at 19:23
3

I think dcast from the reshape2 package has the simplest syntax:

library(reshape2)
dcast(prod ~ day, data=record, value.var='cost')

  prod    1    2
1    1 20.1 15.2
2    2 17.7 23.3

However, this question has been asked many times and will likely be closed quickly.

Justin
  • 42,475
  • 9
  • 93
  • 111