Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

r - add missing rows to a data table

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")),
                 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...