如何在R中编写具有多个条件的ifelse语句?

时间:2018-11-21 08:26:02

标签: r

我在编写ifelse语句时遇到问题,我有三列,如下所示:

default

我想要另一列:结果,如果Team = Winner应该是Winner,否则是失败者,如果Team = anything&Winner = NA,那么应该没有结果...

react-native: 0.57.5
react-native-push-notification: 3.1.2

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

另一种可能是来自case_when的{​​{1}}:

dplyr

数据:

library(dplyr)

df %>% 
  mutate(Result = case_when(
    Team == Winner ~ "Winner",
    Team != Winner ~ "Loser",
    is.na(Winner) ~ "No result"
  ))


#   Team Winner    Result
# 1   T1     T1    Winner
# 2   T2     T1     Loser
# 3   T2   <NA> No result
# 4   T3   <NA> No result

答案 1 :(得分:2)

您可以像我learned一样使用dplyr::if_else(),这很严格,因为它检查数据类型并处理NA,从而使代码更简单:

 df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
  Team Winner    Result
1   T1     T1    Winner
2   T2     T1     Loser
3   T2   <NA> No result
4   T3   <NA> No result

尽管,在这里查看单层解决方案,对于您的示例数据,它并不是最快的(获胜者是@Tim Biegeleisen的答案+1):

Unit: microseconds
    expr      min        lq       mean    median        uq      max neval cld
 IF_ELSE  893.013  974.5060 1176.35331 1053.2260 1343.3590 2278.398   100  b 
  IFELSE   20.481   34.3475   49.57934   47.3605   58.0275  143.361   100 a  
    CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795   100   c

因此,我可以找出在简单性(当然是主观的)和更多控制(即由于函数的性质而客观的)和速度(如果对您而言是个问题,请看一下您的真实情况)之间的权衡数据,但更客观)。

答案 2 :(得分:1)

尝试以下逻辑:

df$result <- ifelse(is.na(df$Winner), "no result",
    ifelse(df$Team==df$Winner, "winner", "loser"))
df

Team Winner    result
1   T1     T1    winner
2   T2     T1     loser
3   T2   <NA> no result
4   T3   <NA> no result

答案 3 :(得分:1)

使用-

df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
df[is.na(df$result), "result"] <- "noresult"
df

输出

  Team.1 Winner   result
1     T1     T1   winner
2     T2     T1    loser
3     T2   <NA> noresult
4     T3   <NA> noresult