Creating a new r data.table column based on values in another column and grouping

后端 未结 2 1265
北海茫月
北海茫月 2020-12-10 06:39

I have a data.table with date, zipcode and purchase amounts.

library(data.table)
set.seed(88)
DT <- data.table(date = Sys.Date()-365 + sort(s         


        
2条回答
  •  眼角桃花
    2020-12-10 07:34

    I didn't find any data.table solutions, this is how I got it though:

    library(dplyr)
    earlierPurchases <- vector()
    
    for(i in 1:nrow(DT)) {
      temp <- dplyr::filter(DT, zip == zip[i] & date < date[i])
      earlierPurchases[i] <- sum(temp$purchaseAmount)
    }
    
    DT <- cbind(DT, earlierPurchases)
    

    It worked quite fast.

提交回复
热议问题