Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over vector containing NULL

Tags:

r

I want to loop over a vector and send the values as parameters to a function. One of the values I want to send is NULL. This is what I've been trying

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

But the loop ignores the NULL value. Any suggestions?

like image 244
Jesse Anderson Avatar asked Jul 24 '12 20:07

Jesse Anderson


2 Answers

The loop doesn't ignore it. Look at things and you'll see that the NULL isn't there.

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

things <- list('M','F',NULL)
for (thing in things) {
  print(thing)
}
[1] "M"
[1] "F"
NULL
like image 133
Joshua Ulrich Avatar answered Nov 08 '22 20:11

Joshua Ulrich


When you construct a vector with c(), a value of NULL is ignored:

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

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

things <- list('M','F',NULL)
for (thing in things){
  print(thing)
}
[1] "M"
[1] "F"
NULL
like image 5
Andrie Avatar answered Nov 08 '22 19:11

Andrie