根据R中其他两个列的几种条件将新列添加到数据框

时间:2019-10-06 09:23:29

标签: r tidyverse

在一个数据框中,我有两列A和B。每列中的值可以是1或NA。
我想添加第三列C:

 - If A == NA AND B == NA, then C = "None"
 - If A == 1 AND B == NA, then C = "A" 
 - If A == NA AND B == 1, then C = "B"
 - if A == 1 AND B == 1, then C = "Both"

2 个答案:

答案 0 :(得分:0)

只需将您的条件转换为case_when条语句

library(dplyr)

df %>%
  mutate(C = case_when(is.na(A) & is.na(B) ~ "None", 
                       A == 1 & is.na(B) ~ "A",
                       B == 1 & is.na(A) ~ "B", 
                       TRUE ~ "Both"))

答案 1 :(得分:0)

我们可以使用ifelse

library(dplyr)
df %>%
    mutate(C = ifelse(is.na(A) & is.na(B), "None",
                   ifelse(A== 1 & is.na(B), "A",
                   ifelse(B==1 & is.na(A), "B",
                   "Both"))))