Loop over a vector containing NULL

I want to iterate over a vector and pass the values ​​as parameters to the function. One of the values ​​I want to send is NULL. This is what I tried

things <- c('M','F',NULL) for (thing in things){ doSomething(thing) } 

But the loop ignores the NULL value. Any suggestions?

+4
source share
2 answers

The loop does not ignore it. Take a look at things and you will see that NULL does not exist.

You cannot mix types in a vector, so you cannot have the types "character" and "NULL" in the same vector. Use a list instead.

 things <- list('M','F',NULL) for (thing in things) { print(thing) } [1] "M" [1] "F" NULL 
+8
source

When you create a vector with c() , the NULL value is ignored:

 things <- c('M','F',NULL) things [1] "M" "F" 

However, if it is important to pass NULL downstream, you can use list instead:

 things <- list('M','F',NULL) for (thing in things){ print(thing) } [1] "M" [1] "F" NULL 
+4
source

All Articles