Warnes, Gregory R
2004-Apr-07 22:50 UTC
[Rd] Re: [R] More user-friendly error message needed.
Perhaps one could create a utility function has.element <- function(list, name) name %in% names(list) and then have $ generate a warning (not an error!) when the named element does not exist. This would be helpful in debugging code. Yesterday I spent quite some time tracking down an error that turned out to be $ returning a NULL because the data file I read in had a variable mis-named. A warning message would have made everything clear right away. -G> -----Original Message----- > From: r-devel-bounces@stat.math.ethz.ch > [mailto:r-devel-bounces@stat.math.ethz.ch]On Behalf Of Duncan Murdoch > Sent: Wednesday, April 07, 2004 4:16 PM > To: Shin; r-devel@stat.math.ethz.ch > Subject: Re: [Rd] Re: [R] More user-friendly error message needed. > > > On Wed, 07 Apr 2004 15:38:54 -0400, Duncan Murdoch <dmurdoch@pair.com> > wrote : > > >There are several places this could be fixed. When you use x$z, the > >code for $ could give an error message or a warning; instead it > >returns NULL with no error or warning. Changing this would probably > >be dangerous: I'd guess there's code out there that relies > on getting > >a NULL back from a construction like that. But maybe we > should change > >that in 2.0? > > No, this would be a bad idea. > > A standard test for the existence of a list element is > > if (is.null(x$z)) .... > > Those would all need some other kind of test if this were changed. > Not a good idea at all! > > Duncan Murdoch > > ______________________________________________ > R-devel@stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailman/listinfo/r-devel >LEGAL NOTICE\ Unless expressly stated otherwise, this messag...{{dropped}}
"Warnes, Gregory R" <gregory_r_warnes@groton.pfizer.com> writes:> Perhaps one could create a utility function > > has.element <- function(list, name) name %in% names(list) > > and then have $ generate a warning (not an error!) when the named element > does not exist.Because of partial matching, list$name can return a result when your has.element function returns FALSE.> lst = list(foo = 1:3, bar = LETTERS[1:3]) > lst$f[1] 1 2 3> has.element <- function(list, name) name %in% names(list) > has.element(lst, "f")[1] FALSE Before we go too far in speculating about what the $ operator should or should not return when the name is not matched, let's all remember that the semantics of the $ operator explicitly state that it should return NULL and, as Duncan wrote, there are many, many places in the base code for R that depend upon this behavior. Trust me - you really don't want to change this.