将缺少的行添加到数据表中

时间:2014-03-17 18:27:34

标签: r 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")),
                 v=1:6,
                 key=c("id1","id2")))
   id1 id2 v
1:   1   a 1
2:   1   c 4
3:   2   a 2
4:   2   b 5
5:   3   b 3
6:   3   d 6
> str(f)
Classes ‘data.table’ and 'data.frame':  6 obs. of  3 variables:
 $ id1: num  1 1 2 2 3 3
 $ id2: Factor w/ 4 levels "a","b","c","d": 1 3 1 2 2 4
 $ v  : int  1 4 2 5 3 6
 - attr(*, "sorted")= chr  "id1" "id2"
 - attr(*, ".internal.selfref")=<externalptr> 

如何添加&#34;缺失&#34;行?

即,对于每个现有id1,我希望id2的所有可能值都存在(使用v=0)。

所以,我需要添加6行(id1的3个可能值* 4 id2的可能值 - 6个现有行。)

2 个答案:

答案 0 :(得分:15)

我会在id1id2中获得唯一值,并使用data.table交叉联接函数CJ进行联接如下:

# 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

答案 1 :(得分:1)

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