条件替换数据框R中的字符元素

时间:2016-01-20 05:04:32

标签: r

我的数据看起来像这样

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

转换后的表应该如下所示

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

但是使用以下代码我得到的数据框不正确

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

我将非常感谢任何有关我出错的地方的帮助

2 个答案:

答案 0 :(得分:4)

你真的不想搞乱因素水平。使用角色要容易得多。首先,让我们将列强制为字符。

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

然后我们可以用矢量子集确定赢/输,然后替换Draw。

with(win_loss_table, {
    replace(c("Won", "Lost")[(Player != Status) + 1L], Status == "Draw", "Draw")
})
# [1] "Won"  "Lost" "Lost" "Draw" "Won"  "Lost" "Lost"

答案 1 :(得分:0)

一种方法是使用嵌套的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