I have a data.table DT
set.seed(1)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
DT
x y v
1: 1 A 29
2: 1 B 92
3: 1 A 100
4: 1 B 82
5: 2 A 28
6: 2 B 26
7: 2 A 18
8: 2 B 22
9: 3 A 30
10: 3 B 96
11: 3 A 15
12: 3 B 4
I would like to expand it like bellow, creating a new column for each value of x
and reporting the v
values, no structure in the data should be expected (not by blocks like bellow)
x y v.1 v.2 v.3
1: 1 A 29 NA NA
2: 1 B 92 NA NA
3: 1 A 100 NA NA
4: 1 B 82 NA NA
5: 2 A NA 28 NA
6: 2 B NA 26 NA
7: 2 A NA 18 NA
8: 2 B NA 22 NA
9: 3 A NA NA 30
10: 3 B NA NA 96
11: 3 A NA NA 15
12: 3 B NA NA 4
I asked a very similar question here but cannot adapt the answer G Grothendieck gave us at the time...
EDIT: As usual I just almost got it after I wrote the post... I just need to replace those 0 by NA (I might get 0 in v and I want to be able to dissociate v==0 from missing items)
DT2 <- DT[, {SUM.<-factor(x); data.table(model.matrix(~ SUM.:v + 0))}]
txtR) DT2
SUM.1:v SUM.2:v SUM.3:v
1: 29 0 0
2: 92 0 0
3: 100 0 0
4: 82 0 0
5: 0 28 0
6: 0 26 0
7: 0 18 0
8: 0 22 0
9: 0 0 30
10: 0 0 96
11: 0 0 15
12: 0 0 4