[R] how to check if an attribute exists

Henrik Bengtsson hb at biostat.ucsf.edu
Thu Feb 3 04:48:13 CET 2011


On Wed, Feb 2, 2011 at 7:25 PM, Peter Langfelder
<peter.langfelder at gmail.com> wrote:
> On Wed, Feb 2, 2011 at 7:22 PM, Nick Matzke <matzke at berkeley.edu> wrote:
>> Oh wait, this basically does it:
>>
>>> if ("a" %in% attributes(z)$names)
>> + print(TRUE)
>> [1] TRUE
>>
>> (but there may be a better way)
>
> If z is a list, you can test
>
> is.null(z$a)

Nope, e.g.

> z <- list(a=NULL)
> str(z)
List of 1
 $ a: NULL

Instead, test by:

> is.element("a", names(z))
[1] TRUE

or equivalently

> ("a" %in% names(z))
[1] TRUE

or

> any(names(z) == "a")
[1] TRUE

My $.02

/Henrik

>
> Peter
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list