当我在 R 中使用 is.na 时,vector 返回 NA 而不是 FALSE

When i use is.na in R, vector is returning NA instead of FALSE

我想使用 ifelse 和 is.na 创建一个新变量。 但问题是这个 ifelse 只返回 1 和 NA。 问题似乎出在我的第一个 ifelse 中,因为我 运行 一个一个地在 ifelse 中,只有第一个返回 NA。看不懂为什么,因为3个ifelse的代码好像都差不多。有人知道吗?

eassociacao<-ifelse((!is.na(dados$CENTRAL)|dados$CENTRAL!=" ") & 
                    (!is.na(dados$SISTEMA)|dados$SISTEMA!=" "),1,
                    ifelse((!is.na(dados$CENTRAL)|dados$CENTRAL!=" ") & 
                           (is.na(dados$SISTEMA)|dados$SISTEMA==" "),2,3))

有 3 个很好的理由不使用嵌套的 ifelse:

  1. 它们不直观,经常会导致错误。
  2. 一年后,当你不得不回到他们身边时,他们很难理解。
  3. 它们的性能不如更清晰的替代品。

这是一个例子:

eassociacao <- rep(NA_integer_, nrow(dados) # initialize
c1 <- !is.na(dados$CENTRAL) & dados$CENTRAL!=" " # condition 1
c2 <- (!is.na(dados$SISTEMA) & dados$SISTEMA!=" ") # condition 2
c3 <- (is.na(dados$SISTEMA) & dados$SISTEMA==" ") # condition 3

eassociacao[c1 & c2] <- 1 # Push 1 where c1 and c2 are TRUE
eassociacao[c1 & c3] <- 2 # Push 2 where c1 and c3 are TRUE
eassociacao[c1 & !c3] <- 3 # Push 3 where c1 and not c3 are TRUE

您可能需要拆分条件才能获得您真正想要的。但是请相信我,当我说这种方法将来会为您节省时间、金钱和费用时。