Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match NA's in switch() loop

Tags:

r

I want to run switch loop and be able to match NA, for example:

    switch(var, match1 = do something, match3 = do something)

How can do it if var is NA like so:

    switch(var, match1 = do something, match3 = do something, NA = do something)

I've also tried is.na() instead of NA and it didn't work.

like image 935
ramses Avatar asked May 27 '15 11:05

ramses


1 Answers

In this situation, NA has to be escaped using backticks (or quotes)

switch(var, match1 = do something, `NA` = do something)

One thing to note is that you cannot switch NA values directly. For example

switch(NA, `NA` = 1)

does not work, and you should use e.g.

switch(as.character(NA), `NA` = 1)
# [1] 1

instead. It is probably better to use var[is.na(var)] <- ...

like image 53
konvas Avatar answered Oct 25 '22 15:10

konvas