lundi 19 août 2019

R: Testing a variable that possibly doesn't exist

I assume this is a common problem but haven't been able to find an answer to this question. Let's assume I have the following list:

myList <- list(
  apple = 15,
  orange = NULL
)

I want to test its vectors for values, although I cannot be sure that these vectors exist when i perform the test.

if(myList$apple > 1) print("Y")
if(myList$orange > 1) print("Y")
if(myList$banana > 1) print("Y")

This obviously doesn't work

Error in if (myList$orange > 1) print("Y") : argument is of length zero
Error in if (myList$banana > 1) print("Y") : argument is of length zero

However, for I want to avoid nested testing with exists() for reasons that would require too much detail. So my question is: Can a test on a variable that possibly doesn't exist be performed in only one conditional statement?

Thanks

Aucun commentaire:

Enregistrer un commentaire