add missing rows to a data table

后端 未结 2 1264
臣服心动
臣服心动 2020-12-06 07:12

I have a data table:

library(data.table)
(f <- data.table(id1=c(1,2,3,1,2,3),
                 id2=as.factor(c(\"a\",\"a\",\"b\",\"c\",\"b\",\"d\")),
             


        
相关标签:
2条回答
  • 2020-12-06 07:38
    f[, {
      tab = table(id2)
      x = as.numeric(tab)
      x[x != 0] = v
      list(id2 = names(tab), v = x)
    }, by = id1]
    
    ##    id1 id2 v
    ##  1:   1   a 1
    ##  2:   1   b 0
    ##  3:   1   c 4
    ##  4:   1   d 0
    ##  5:   2   a 2
    ##  6:   2   b 5
    ##  7:   2   c 0
    ##  8:   2   d 0
    ##  9:   3   a 0
    ## 10:   3   b 3
    ## 11:   3   c 0
    ## 12:   3   d 6
    
    0 讨论(0)
  • 2020-12-06 07:48

    I'd get the unique values in id1 and id2 and do a join using data.table's cross join function CJ as follows:

    # if you've already set the key:
    ans <- f[CJ(id1, id2, unique=TRUE)][is.na(v), v := 0L][]
    
    # or, if f is not keyed:
    ans <- f[CJ(id1 = id1, id2 = id2, unique=TRUE), on=.(id1, id2)][is.na(v), v := 0L][]
    
    ans
    
    0 讨论(0)
提交回复
热议问题