3

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?

Community
  • 1
  • 1
beginneR
  • 3,207
  • 5
  • 30
  • 52

1 Answers1

5

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.

Matt Dowle
  • 58,872
  • 22
  • 166
  • 224