在一个数据框中,我有两列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"
答案 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"))))