Enrico Enrico - 7 days ago 4
R Question

Rearranging tables in R: column as variables

I have a data.frame as follows:

df1 = data.table(Year=c(2009,2009, 2009,2010, 2010, 2010,2011,2011,2011), ID =c(162, 163,164,162, 163,164,162, 163,164), sum = c(2,5,6,3,4,6,4,2,7) )


I would like to rearrange df1 in such a way that the items of the variable "ID" are the new columns (or variable names) and the different years in variable "Year" become the rows. The third variable "sum" should complete table.

The desired output is as follows:

df2 = data.table(Year=c(2009, 2010, 2011), "162" = c(2,3,4 ), "163" = c( 5,4,2), "164" = c(6,6,7) )


Any smart solution?

Answer
   library(data.table)
 df2<-dcast(df1,Year~ID)