Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transpose-like procedure in data.table

Tags:

r

data.table

I asked a similar yet different question before (here)

Now I wanna change this dataset:

dt <- data.table(a=c("A","A","A"),b=1:3,c=c(0,1,0))
dt
   a b c
1: A 1 0
2: A 2 1
3: A 3 0

to this one:

   a 1 2 3
1: A 0 1 0

So values of column "b" should become columns each with the value of column "c". Values of "a" can be seen as participants (here just one Person ("A"). The original dataset continues with multiple values of B and so on. After "transposing", column "a" should include unique values (e.g. A,B,C etc)

Any suggestions?

like image 593
beginneR Avatar asked Dec 12 '25 05:12

beginneR


1 Answers

I think I can see where you're going with this.

The following should cope with varying unique items in b as well and line them up.

.u = unique(dt$b)                        # find first the unique columns
ans = dt[,as.list(c[match(.u,b)]),by=a]  # as.list is the way to make columns
setnames(ans,c("a",.u))                  # rename once afterwards is faster
ans
   a 1 2 3
1: A 0 1 0

Untested on more complex cases.

like image 138
Matt Dowle Avatar answered Dec 13 '25 23:12

Matt Dowle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!