2

My data looks like this

win_loss_table<- data.frame(Player = c("A","B","C","D","E","A","C"),Status = c("A","C","D","Draw","E","C","D"))
> win_loss_table
  Player Status
1      A      A
2      B      C
3      C      D
4      D   Draw
5      E      E
6      A      C
7      C      D

The transformed table should look like this

desired_table <- data.frame(Player = c("A","B","C","D","E","A","C"), Status= c("Won","Lost","Lost","Draw","W0n","Lost","Lost"))
> desired_table
  Player Status
1      A    Won
2      B   Lost
3      C   Lost
4      D   Draw
5      E    Won
6      A   Lost
7      C   Lost

However using the following code I am getting a data frame like this which is incorrect

incorrect_table<- data.frame(Player = c("A","B","C","D","E","A","C"),Status=as.factor(ifelse(win_loss_table$Status == "Draw","Draw",ifelse(win_loss_table$Player %in% win_loss_table$Status,"Won","Lost"))))
>incorrect_table
  Player Status
1      A    Won
2      B   Lost
3      C    Won
4      D   Draw
5      E    Won
6      A    Won
7      C    Won

Any help on where I am going wrong willl be greatly appreciated

Rajarshi Bhadra
  • 1,826
  • 6
  • 25
  • 41
  • I think the problem was here: `ifelse(win_loss_table$Player %in% win_loss_table$Status,"Won","Lost")` , which does not compare value against value but looks each value in the first list (`win_loss_table$Player`) inside the second one `win_loss_table$Status`. A simple `==` does the job, as shown in the answers. – Carlos Alberto Jan 20 '16 at 06:36

2 Answers2

4

You don't really want to be messing around with factor levels. It's much easier to work with characters. First let's coerce the columns to character.

win_loss_table[] <- lapply(win_loss_table, as.character)

Then we can determine the Win/Loss with a vector subset then replace the Draw afterward.

with(win_loss_table, {
    replace(c("Won", "Lost")[(Player != Status) + 1L], Status == "Draw", "Draw")
})
# [1] "Won"  "Lost" "Lost" "Draw" "Won"  "Lost" "Lost"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

One way, would be using nested ifelse

as.factor(ifelse(as.character(win_loss_table$Player) == as.character(win_loss_table$Status), "Won",
   ifelse(as.character(win_loss_table$Status) == "Draw", "Draw", "Lost")))

#[1] Won  Lost Lost Draw Won  Lost Lost
#Levels: Draw Lost Won

data.frame(Player = c("A","B","C","D","E","A","C"), Status = factor(ifelse(as.character(win_loss_table$Player) == as.character(win_loss_table$Status), "Won",
                                                                       ifelse(as.character(win_loss_table$Status) == "Draw", "Draw", "Lost"))))

#  Player Status
#1      A    Won
#2      B   Lost
#3      C   Lost
#4      D   Draw
#5      E    Won
#6      A   Lost
#7      C   Lost
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213