-3

I have a data frame which looks like this

> initial
  Name Status
1    a    Win
2    b    Win
3    c   Loss

From here I want a data frame which looks like this

> final
  Name Win Loss
1    a   1    0
2    b   1    0
3    c   0    1

How can I achieve this

Rajarshi Bhadra
  • 1,826
  • 6
  • 25
  • 41

3 Answers3

2

How about using the base function table?

initial=data.frame(name=c("a","b","c"),
                   status=c("win","loss","win"))
  name status
1    a    win
2    b   loss
3    c    win


table(initial)

  name loss win
   a    0   1
   b    1   0
   c    0   1

The function table returns a table object. To convert it to a data.frame of the sort you like, using the command as.data.frame will not help, since that dispatches the function as.data.frame.table. Instead you should pass the table to as.data.frame.matrix

final_data_frame= as.data.frame.matrix(table(initial)) 
1

We can use dcast

library(reshape2)
dcast(initial, Name~Status, value.var='Status', length)
#  Name Loss Win
#1    a    0   1
#2    b    0   1
#3    c    1   0
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Use model.matrix() to create the columns:

model.matrix(Name ~ -1 + Status, data = initial)

  StatusLoss StatusWin
1          0         1
2          0         1
3          1         0
J.R.
  • 3,838
  • 1
  • 21
  • 25