问题
My code is:
data$E<-ifelse(data$D==data$B, "b", ifelse(data$D==data$C, "c", "unknowwn"))
result:
A B C D E
1 16 16 NA 16 b
2 20 NA 20 20 NA
3 24 NA NA 24 NA
But what I want is:
A B C D E
1 16 16 NA 16 b
2 20 NA 20 20 c
3 24 NA NA 24 unknowwn
Dose anyone know how to solve this problem? Thanks!
回答1:
data$E <- ifelse(!is.na(data$B) & data$D == data$B, "b",
ifelse(!is.na(data$C) & data$D == data$C, "c", "unknowwn"))
回答2:
Your condition is a bit complicated as you need to consider if either of columns B
, C
or D
contains NA
. Hence, you can try consider using dplyr::case_when
as:
Edited: Based on suggestion from @A.Suliman
there is no need to have checking for is.na
with case_when
.
library(dplyr)
data %>% mutate( E = case_when(
D==B ~ "b",
D==C ~ "c",
TRUE ~ "Unknown"
))
# A B C D E
# 1 16 16 NA 16 b
# 2 20 NA 20 20 c
# 3 24 NA NA 24 Unknown
Data:
data <- read.table(text=
"A B C D
1 16 16 NA 16
2 20 NA 20 20
3 24 NA NA 24",
header = TRUE)
来源:https://stackoverflow.com/questions/51348877/use-ifelse-to-create-new-column-in-r