多个if-else条件的最简单方法是什么?

时间:2019-11-28 15:42:46

标签: r dplyr

我有一个类似这样的数据集:

df_1 <- tribble(
  ~A,   ~B,  ~C,  
  10,   10,  NA,        
  NA,   34,  15,       
  40,   23,  NA,
   4,   12,  18,
)

现在,我只想比较每一行的A,B,C,并添加一个新列来显示最小数量。让我们看一下所需数据的样子:

df_2 <- tribble(
  ~A,  ~B,  ~C,  ~Winner,
  10,  10,  NA,  "Same",     
  NA,  34,  15,  "C",     
  40,  23,  NA,  "B",   
   4,  12,  18,  "A",
)

有四个输出:相同,A-Win,B-Win,C-Win。

您将如何编码以获得此结果?

先谢谢了。

2 个答案:

答案 0 :(得分:2)

这是东西:

foo <- function(x) {
  rmin <- which(x == min(x, na.rm = TRUE))
  if (length(rmin) > 1) "same" else names(rmin)
}
apply(df_1, 1,  foo)

[1] "same" "C"    "B"    "A"  

您可以使用以下方法将此列添加到data.frame中:

df_1$winner <- apply(df_1, 1,  foo)

# A tibble: 4 x 4
      A     B     C winner
  <dbl> <dbl> <dbl> <chr> 
1    10    10    NA same  
2    NA    34    15 C     
3    40    23    NA B     
4     4    12    18 A    

如果您有更多变量,并且只想使用一些变量,则可以使用字符向量:

vars <- c("A", "B", "C")
apply(df_1[vars], 1,  foo)

答案 1 :(得分:0)

df_1 <- tribble(
  ~A,   ~B,  ~C,  
  10,   10,  NA,        
  NA,   34,  15,       
  40,   23,  NA,
  4,    12,  18,
)

df_1 %>%
  mutate(
    winner = colnames(df_1)[apply(df_1,1,which.min)],
    winner = if_else(A == B | B == C | A == C, 'same', winner, missing = winner))

# A tibble: 4 x 4
      A     B     C winner
  <dbl> <dbl> <dbl> <chr> 
1    10    10    NA same  
2    NA    34    15 C     
3    40    23    NA B     
4     4    12    18 A