Testing whether a list contains an element

In the past I have always used is.null() in R to test whether a list contains a specified element. E.g., if I wanted to know whether a list, mylist contained the element x I would have used

is.null(mytest$x)

This failed me today when I tried to test if a list contained an element M when it also contained an element Mtot. Because R completes names of elements in lists, the call mylist$M will return the first element in the list whose name begins with M. This means that if the list contains Mtot (or any other elements whose name starts with M then mylist$M will be TRUE. Here is an example:


> mylist <- list(Mtot = 5)
> is.null(mylist$M)
[1] FALSE
> mylist$M
[1] 5

The (much better) way around this is the function exists. For example:


> exists("M", mylist)
[1] FALSE
> exists("Mtot", mylist)
[1] TRUE
This entry was posted in Programming, R. Bookmark the permalink.