I'll pick an example with unequal groups so that it's easier to illustrate for the general case:
A <- data.table(x=c(1,1,1,2,2), y=c(1,2,3,1,2), v=(1:5)/5)
> A
x y v
1: 1 1 0.2
2: 1 2 0.4
3: 1 3 0.6
4: 2 1 0.8
5: 2 2 1.0
The first step is to get the number of elements/entries for each group of "x" to be the same. Here, for x=1 there are 3 values of y, but only 2 for x=2. So, we'll have to fix that first with NA for x=2, y=3.
setkey(A, x, y)
A[CJ(unique(x), unique(y))]
Now, to get it to wide format, we should group by "x" and use as.list
on v
as follows:
out <- A[CJ(unique(x), unique(y))][, as.list(v), by=x]
x V1 V2 V3
1: 1 0.2 0.4 0.6
2: 2 0.8 1.0 NA
Now, you can set the names of the reshaped columns using reference with setnames
as follows:
setnames(out, c("x", as.character(unique(A$y)))
x 1 2 3
1: 1 0.2 0.4 0.6
2: 2 0.8 1.0 NA
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…