[R] Indexing Lists and Partial Matching

Liaw, Andy andy_liaw at merck.com
Thu Jan 27 16:13:11 CET 2005


This has been discussed a few times on this list before, so you might want
to dig into the archive...

You might want to check existence of name instead of checking whether the
component is NULL:

> x <- list(bc="bc", ab="ab")
> is.null(x$b)
[1] FALSE
> "b" %in% names(x)
[1] FALSE

Andy


> From: McGehee, Robert
> 
> I was unaware until recently that partial matching was used to index
> data frames and lists. This is now causing a great deal of problems in
> my code as I sometimes index a list without knowing what elements it
> contains, expecting a NULL if the column does not exist. However, if
> partial matching is used, sometimes R will return an object I do not
> want. My question, is there an easy way of getting around this?
> 
> For example:
> > a <- NULL
> > a$abc <- 5
> > a$a
> [1] 5
> > a$a <- a$a
> > a
> $abc
> [1] 5
> $a
> [1] 5
> 
> Certainly from a coding prospective, one might expect assigning a$a to
> itself wouldn't do anything since either 1) a$a doesn't exist, so
> nothing happens, or 2) a$a does exist and so it just assigns its value
> to itself. However, in the above case, it creates a new 
> column entirely
> because I happen to have another column called a$abc. I do 
> not want this
> behavior.
> 
> The solution I came up with was to create another indexing 
> function that
> uses the subset() (which doesn't partial match), then check for an
> error, and if there is an error substitute NULL (to mimic the "["
> behavior). However, I don't really want to start using 
> another indexing
> function altogether just to get around this behavior. Is 
> there a better
> way? Can I turn off partial matching?
> 
> Thanks,
> Robert
> 
> 
> Robert McGehee
> Geode Capital Management, LLC
> 53 State Street, 5th Floor | Boston, MA | 02109
> Tel: 617/392-8396    Fax:617/476-6389
> mailto:robert.mcgehee at geodecapital.com
> 
> 
> 
> This e-mail, and any attachments hereto, are intended for 
> us...{{dropped}}
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list