Is it possible to distinguish between NA_character_ and "NA" in `switch`?

In Corresponding to NA in the switch () loop , the responder indicated that using `NA`in switchwould correspond to missing values. However, "NA"also consistent. I have a character vector that contains both a string "NA"and missing values NA. I pass the elements of this vector one by one before switch, but cannot distinguish between two

for (k in c(NA, "NA")) {
  cat(switch(k, "NA_character_" = "C", "NA" = "B", `NA` = "A"))
}

#> BB

for (k in c(NA, "NA")) {
  cat(switch(k, "NA_character_" = "C", `NA` = "A", "NA" = "B"))
}

#> AA

I know what I could use if (is.na(k))to distinguish them, but the purpose of use switchwas to restrict nested statements if ... else, so I would prefer to use it only switchif it is just a matter of choosing the right name in the list of alternatives. I note that the help file says (with my accent):

If EXPR evaluates a character string, then that string matches (exactly) the names of the elements in ...

therefore, I wonder if there is a specific “exactly equal NA_character_value that is applicable here.

+4
source share
1 answer

We can create a function to distinguish between three cases.

f1 <- function(val){      
   switch(deparse(val),
      "NA_character_" = "C", 
       "NA" = "B", 
      '"NA"' = "A") 
 }

f1(NA)
[1] "B"
f1(NA_character_)
#[1] "C"
f1("NA")   
#[1] "A"

Using OP loop

for(k in c(NA, "NA")) cat(f1(k), "\n")
#C
#A

NA NA_character_, . NA, list

for(k in list(NA, "NA")) cat(f1(k), "\n")
#B 
#A 
+4

Source: https://habr.com/ru/post/1692079/


All Articles