If we use ==
, make sure to also add is.na
to return TRUE/FALSE, otherwise, the NAs remain as NA
(如果我们使用==
,请确保还添加is.na
以返回TRUE / FALSE,否则,NA仍为NA)
library(dplyr)
df%>%
mutate(new_name = ifelse(status=="unaccepted" & !is.na(status),valid_name,
ifelse(status=="accepted" & !is.na(status),species,NA)))
# species valid_name status new_name
#1 Tilapia guineensis <NA> <NA> <NA>
#2 Tilapia zillii Hippocampus trimaculatus unaccepted Hippocampus trimaculatus
#3 Fundulus rubrifrons Hippocampus trimaculatus unaccepted Hippocampus trimaculatus
#4 Eutrigla gurnardus Bougainvillia supercili accepted Eutrigla gurnardus
#5 Sprattus sprattus <NA> <NA> <NA>
#6 Gadus morhua Aglantha digitale accepted Gadus morhua
Another option is to use %in%
which will return FALSE for NA
(另一种选择是使用%in%
,它将为NA返回FALSE)
df%>%
mutate(new_name = ifelse(status %in% "unaccepted" ,valid_name,
ifelse(status %in% "accepted",species,NA)))
using a reproducible example
(使用可复制的示例)
v1 <- c('a', 'b', NA)
v1 == 'a'
#[1] TRUE FALSE NA ####
v1 %in% 'a'
#[1] TRUE FALSE FALSE
data (数据)
df <- structure(list(species = c("Tilapia guineensis", "Tilapia zillii",
"Fundulus rubrifrons", "Eutrigla gurnardus", "Sprattus sprattus",
"Gadus morhua"), valid_name = c(NA, "Hippocampus trimaculatus",
"Hippocampus trimaculatus", "Bougainvillia supercili", NA,
"Aglantha digitale"
), status = c(NA, "unaccepted", "unaccepted", "accepted", NA,
"accepted")), class = "data.frame", row.names = c(NA, -6L))