Problem
I would like to test if an element of a list exists, here is an example
foo <- list(a=1)
exists('foo')
TRUE #foo does exist
exists('foo$a')
FALSE #suggests that foo$a does not exist
foo$a
[1] 1 #but it does exist
In this example, I know that foo$a exists, but the test returns FALSE.
I looked in ?exists and have found that with(foo, exists('a') returns TRUE, but do not understand why exists('foo$a') returns FALSE.
Questions
- Why does
exists('foo$a')returnFALSE? - Is use of
with(...)the preferred approach?
This is actually a bit trickier than you’d think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check
is.null(foo$a). A more stringent test might be to check that the name is actually defined in the list:…and
foo[["a"]]is safer thanfoo$a, since the latter uses partial matching and thus might also match a longer name:[UPDATE] So, back to the question why
exists('foo$a')doesn’t work. Theexistsfunction only checks if a variable exists in an environment, not if parts of a object exist. The string"foo$a"is interpreted literary: Is there a variable called “foo$a”? …and the answer isFALSE…