DJJ
DJJ

Reputation: 2539

dcast long to wide by transforming unique RHS

Let's say I have a table like the following:

DT <- data.table(ID1= rep(c("a","b","c"),3),ID2=rnorm(9,4),var = 1:9)

## > DT
##    ID1      ID2 var
## 1:   a 2.630392   1
## 2:   b 3.966620   2
## 3:   c 4.002776   3
## 4:   a 3.188372   4
## 5:   b 4.735084   5
## 6:   c 4.307198   6
## 7:   a 2.830868   7
## 8:   b 4.892684   8
## 9:   c 3.429826   9

and I would like to perform a dcast with the by taking into consideration only the number of times that each ID1 apprear.

undesired output:

dcast(DT,ID1~ID2)

desired output:

##    ID1 1 2 3
## 1:   a 1 4 7
## 2:   b 2 5 8
## 3:   c 3 6 9

Upvotes: 1

Views: 60

Answers (1)

akrun
akrun

Reputation: 887048

Try

dcast.data.table(DT[,N:=1:.N ,ID1], ID1~N, value.var='var')
#   ID1 1 2 3
#1:   a 1 4 7
#2:   b 2 5 8
#3:   c 3 6 9

Upvotes: 2

Related Questions