merlin2011 merlin2011 - 3 years ago 204
R Question

In R, how can I check whether a list contains a particular key?

Suppose I have a list as follows

foo=list(bar="hello world")

I would like to check whether my list has a particular key.
I observe
will return
for any
that is not equal to
, so I figured I could check for whether the return value was null, but this does not seem to work:

if (foo$bar2==NULL) 1 # do something here

However, this gives the error:

Error in if (foo$bar2 == NULL) 1 : argument is of length zero

I then tried whether NULL is equivalent to false, like in C:

if (foo$bar2) 1 # do something here

This gives the same error.

I now have two questions. How can I check whether the list contains the key?
And how do I check whether an expression is null?

42- 42-
Answer Source

The notion of "keys" are called "names" in R.

if ("bar" %in% names(foo) ) {  print("it's there") }  # ....

They are stored in a special attribute named .Names and extracted with the names function:

#structure(list(bar = "hello world"), .Names = "bar")

I offer a semantic caution here, because of a common source of confusion due to two distinct uses of the word: "names" in R: There are .Names-attributes, but there is an entirely different use of the word name in R that has to do with strings or tokens that have values independent of any inspection or extraction functions like $ or [. Any token that starts with a letter or a period and has nor other special characters in it can be a valid name. One can test for it with the the function exists given a quoted version of its name:

 exists("foo")  # TRUE
 exists(foo$bar) #    [1] FALSE
 exists("foo$bar")#    [1] FALSE

So the word name has two different meanings in R and you will need to be aware of this ambiguity to understand how the language is deployed. The .Names meaning refers to an attribute with special purposes, while the names-meaning refers to what is called a "language-object". The word symbol is a synonym for this meaning of the word. quote(foo) ) #[1] TRUE

To then show how your second question about testing for nullity might flow into this :

if( !is.null(foo$bar) ) {  print("it's there") }  # any TRUE value will be a 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download