向数据表添加缺少的行

向数据表添加缺少的行

本文介绍了向数据表添加缺少的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个数据表: (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 存在(与 v = 0 ) * 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 v1: 1 a 12: 1 c 43: 2 a 24: 2 b 55: 3 b 36: 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 keyans <- f[CJ(unique(id1), unique(id2))][is.na(v), v := 0L]ans 这篇关于向数据表添加缺少的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 00:37