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 foo$bar2
will return NULL
for any bar2
that is not equal to bar
, 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?
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:
dput(foo)
#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 second meaning of the word.
is.name( 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.