jeudi 12 novembre 2015

How to have stopifnot() return an error when called on a missing (NULL) element of a list?

With stopifnot(), how to test an element in a list, also checking that the element itself exists?

For example li is a list, which contains an item. I want to ensure that item is equal to 0.

li <- list()
li$item <- 1
stopifnot(li$item == 0)
# Error: l$x == 0 is not TRUE

Returned an error, which is what I want. But if I make a typo and enter :

stopifnot(li$tem == 0)

R doesn't return an error. Even though this element doesn't exist in the list:

li$tem
# NULL

Why R doesn't tell me that the element 'tem' is not found in the list?

li$tem == 0

evaluates to logical(0).

Aucun commentaire:

Enregistrer un commentaire