A reshape puzzle in data.table

后端 未结 3 563
遥遥无期
遥遥无期 2021-01-19 13:07

Yet another reshape problem in data.table

set.seed(1234)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c(\"A\",\"B\"), v=sample(1:100,12))
#             


        
3条回答
  •  情深已故
    2021-01-19 13:58

    Not sure this is the best solution, but you could do something like the following.

    set.seed(1234)
    DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
    DT[, id := seq_len(nrow(DT))]
    
    setkey(DT, y)
    
    uniqY <- unique(DT$y)
    
    for(jj in uniqY){
      nc <- do.call(paste, c(expand.grid('Sum', c('x','v'),jj), sep ='.'))
      DT[.(jj), (nc) := list(cumsum(x), cumsum(v))]
    
    }
    
    setkey(DT, id)
    
    DT[, 5:8 := lapply(.SD, function(x) { 
      xn <- is.na(x)
      x[xn] <- -Inf
      xx <- cummax(x)
      # deal with leading NA values
        if(xn[1]){
        xn1 <- which(xn)[1]
      xx[seq_len(xn1)] <- NA}   
    
      xx }), .SDcols = 5:8]
    

提交回复
热议问题