1

I have a data frame:

df <- data.frame(month=rep(1:3,2), ID=rep(1:2,each=3),  
                 year=rep(2012,6),tmin=c(1:6),tmax=c(7:12))

And I want to have a data frame like:

df1 <- data.frame(ID=rep(1:2,each=2), weather=rep(c("tmin","tmax"),2),
                  year=rep(2012,4), m1=c(1,7,4,10), m2=c(2,8,5,11),
                  m3=c(3,9,6,12))

In real data there are thousands data for 12 months, but basically I hope to transpose the data frame by column of month, I've tried using t and aggregate, and also searched around, but with no success, any help would be appreciated, thanks.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Rosa
  • 1,793
  • 5
  • 18
  • 23

1 Answers1

1

Yup, reshape2 would be my first thought:

library(reshape2)
dcast(melt(df,id.vars = 1:3),ID + variable + year ~ month,fun.aggregate = sum,value.var = "value")
  ID variable year  1  2  3
1  1     tmin 2012  1  2  3
2  1     tmax 2012  7  8  9
3  2     tmin 2012  4  5  6
4  2     tmax 2012 10 11 12

Only thing left is to rename the columns, if you like.

joran
  • 169,992
  • 32
  • 429
  • 468