Create a panel data frame

后端 未结 3 1829
借酒劲吻你
借酒劲吻你 2021-01-06 13:58

I would like to create a panel from a dataset that has one observation for every given time period such that every unit has a new observation for every time period. Using th

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 14:09

    Using data.table:

    require(data.table)
    DT <- data.table(frame, key=c("id", "year"))
    comb <- CJ(1:4, 2005:2008) # like 'expand.grid', but faster + sets key
    ans <- DT[comb][is.na(y), y:=0L] # perform a join (DT[comb]), then set NAs to 0
    #     id year y
    #  1:  1 2005 1
    #  2:  1 2006 0
    #  3:  1 2007 0
    #  4:  1 2008 0
    #  5:  2 2005 0
    #  6:  2 2006 0
    #  7:  2 2007 0
    #  8:  2 2008 0
    #  9:  3 2005 0
    # 10:  3 2006 0
    # 11:  3 2007 0
    # 12:  3 2008 0
    # 13:  4 2005 0
    # 14:  4 2006 0
    # 15:  4 2007 1
    # 16:  4 2008 0
    

提交回复
热议问题