Question

I've a large data.table which looks like

custid, dayofweek, revenue
AA 2 345
AA 3 545
BB 1 544
BB 4 456
CC 7 231

I would like to "grow" this data table such that it has all 7 numbers for each custid with the revenue column set to NA. Example shown below.

custid, dayofweek, revenue
AA 1 NA
AA 2 345
AA 3 545
AA 4 NA
AA 5 NA
AA 6 NA
AA 7 NA
BB 1 544
BB 2 NA
BB 3 NA
BB 4 456
BB 5 NA
BB 6 NA
BB 7 NA
CC 1 NA
CC 2 NA
CC 3 NA
CC 4 NA
CC 5 NA
CC 6 NA
CC 7 231

Growing it that way is definitely not a join operation. Any help appreciated. Thanks in advance.

Was it helpful?

Solution

setkey(dt, custid, dayofweek)
dt[CJ(unique(custid), 1:7)]
#    custid dayofweek revenue
# 1:     AA         1      NA
# 2:     AA         2     345
# 3:     AA         3     545
# 4:     AA         4      NA
# 5:     AA         5      NA
# 6:     AA         6      NA
# 7:     AA         7      NA
# 8:     BB         1     544
# 9:     BB         2      NA
#10:     BB         3      NA
#11:     BB         4     456
#12:     BB         5      NA
#13:     BB         6      NA
#14:     BB         7      NA
#15:     CC         1      NA
#16:     CC         2      NA
#17:     CC         3      NA
#18:     CC         4      NA
#19:     CC         5      NA
#20:     CC         6      NA
#21:     CC         7     231
#    custid dayofweek revenue
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top