向数据表添加缺少的行 [英] add missing rows to a data table

查看:79
本文介绍了向数据表添加缺少的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表:

 (f  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'和'data.frame':6 obs。的3个变量:
$ id1:num 1 1 2 2 3 3
$ id2:因子w / 4级a,b,c,d:1 3 1 2 2 4
$ v:int 1 4 2 5 3 6
- attr(*,sorted)= chrid1id2
- attr(*,.internal。 selfref)=< externalptr>

如何添加缺少的行?


$ b $对于每个现有的 id1 我想要所有可能的值 id2 存在(与<$因此,我需要添加6行(3个可能的值 c $ c> v = 0 )



< id1 * 4个可能的值 id2 - 6个现有行)。

解决方案

我会得到 id1 id2 中的唯一值, data.table 交叉连接函数 CJ 如下:

 #您已经设置了键
ans< - f [CJ(unique(id1),unique(id2))] [is.na(v),v:= 0L]
ans


I have a 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> 

How do I add the "missing" rows?

I.e., for each existing id1 I want all possible values of id2 to be present (with v=0).

So, I need to add 6 rows (3 possible values of id1 * 4 possible values of id2 - 6 existing rows).

解决方案

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

# you've already set the key
ans <- f[CJ(unique(id1), unique(id2))][is.na(v), v := 0L]
ans

这篇关于向数据表添加缺少的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆