Create count per item by year/decade

后端 未结 2 1793
我在风中等你
我在风中等你 2021-01-24 02:04

I have data in a data.table that is as follows:

> x<-df[sample(nrow(df), 10),]
> x      

>                   Importer                 Exporter               


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 02:46

    We can do this using data.table methods, Create the 'Decade' column by assignment :=, then melt the data from 'wide' to 'long' format by specifying the measure columns, reshape it back to 'wide' using dcast and we use the fun.aggregate as length.

    x[, Decade:= year(Date) - year(Date) %%10]
    dcast(melt(x, measure = c("Importer", "Exporter"), value.name = "Country"), 
                           Decade + Country~variable, length)
    #     Decade        Country Importer Exporter
    # 1:   2000      Australia        1        0
    # 2:   2000        Ecuador        1        0
    # 3:   2000          India        1        0
    # 4:   2000         Israel        1        1
    # 5:   2000           Peru        1        1
    # 6:   2000 United Kingdom        0        1
    # 7:   2000  United States        1        3
    # 8:   2010         France        0        1
    # 9:   2010      Guatemala        1        1
    #10:   2010          India        1        0
    #11:   2010         Mexico        1        0
    #12:   2010         Poland        1        0
    #13:   2010  United States        0        2
    

提交回复
热议问题