Checking if variable is set or not

Not exactly a game-breaking bug, but I was curious on how people generally would deal with this.

I have set a list variable that is initialised with a default value of NA. But, this value gets replaced with a list (so list within a list) if the user sets the value.

So when I put this into an if statement, it will only check for the first element in the list:

if (!is.na(list1$list2)) {
  ...
}
# the condition has length > 1 and only the first element will be used

So the potential problem is if the first element is, by off chance, NA. It won't be 99% of the time, but I'm trying to prevent the exception.

I just want to check if the variable has been altered or not from the initial state. What would be the right solution for this?

Hi there,

I find the logic a bit weird, but that's probably because I don't know the larger context. Whenever I need to set a variable and then later check for it, I use the NULL which will create an empty object. So whatever the user inputs (including NA and regardless of the number of items) will be different.

myList = NULL

if(is.null(myList)){
  print("Empty")
} else {
  print("Not empty")
}
#> [1] "Empty"


myList = list(NA, list(5))

if(is.null(myList)){
  print("Empty")
} else {
  print("Not empty")
}
#> [1] "Not empty"

Created on 2022-03-09 by the reprex package (v2.0.1)

Hope this helps,
PJ

Ah thanks, but I should have mentioned that it must be NA, not NULL. I'm unsure if the same logic would be applicable for NULL -- they are handled differently.

HI,

That is exactly why I suggested this solution. Could you provide an actual example where this issue surfaces, because I don't understand what it is you want now :slight_smile:

Try and create a reprex. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

Good luck

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.