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

时间:2015-11-12 11:08:13

标签: r testing

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).

1 个答案:

答案 0 :(得分:2)

The problem here is not so much the stopifnot() function, but rather the use of == for doing the comparison:

# returns an empty logical vector, not TRUE or FALSE:
li$tem == 0 # logical(0)
# according to ?`==` we should use identical() instead of ==:
identical(li$tem, 0) # returns FALSE
# this now works as it should, i.e. it throws an error:
stopifnot(identical(li$tem, 0))

From ?"==":

Do not use == and != for tests, such as in if expressions, where you must get a single TRUE or FALSE. Unless you are absolutely sure that nothing unusual can happen, you should use the identical function instead.