Skip to content
Prev 49600 / 63421 Next

RFC: getifexists() {was [Bug 16065] "exists" ...}

Adding an optional argument to get (and mget) like

val <- get(name, where, ..., value.if.not.found=NULL )   (*)

would be useful for many.  HOWEVER, it is possible that there could be 
some confusion here: (*) can give a NULL because either x exists and 
has value NULL, or because x doesn't exist.   If that matters, the user 
would need to be careful about specifying a value.if.not.found that cannot 
be confused with a valid value of x.  

To avoid this difficulty, perhaps we want both: have Martin's getifexists( ) 
return a list with two values: 
  - a boolean variable 'found'  # = value returned by exists( )
  - a variable 'value'

Then implement get( ) as:

get <- function(x,...,value.if.not.found ) {

  if( missing(value.if.not.found) ) {
    a <- getifexists(x,... )
    if (!a$found) error("x not found")
  } else {
    a <- getifexists(x,...,value.if.not.found )
  }
  return(a$value)
}

Note that value.if.not.found has no default value in above.
It behaves exactly like current get does if value.if.not.found 
is not specified, and if it is specified, it would be faster 
in the common situation mentioned below:   
     if(exists(x,...)) { get(x,...) }

John

P.S. if you like dromedaries call it valueIfNotFound ...

 ..............................................................
 John P. Nolan
 Math/Stat Department
 227 Gray Hall,   American University
 4400 Massachusetts Avenue, NW
 Washington, DC 20016-8050

 jpnolan at american.edu       voice: 202.885.3140          
 web: academic2.american.edu/~jpnolan
 ..............................................................


-----"R-devel" <r-devel-bounces at r-project.org> wrote: ----- 
To: Martin Maechler <maechler at stat.math.ethz.ch>, R-devel at r-project.org
From: Duncan Murdoch 
Sent by: "R-devel" 
Date: 01/08/2015 06:39AM
Subject: Re: [Rd] RFC: getifexists() {was [Bug 16065] "exists" ...}
On 08/01/2015 4:16 AM, Martin Maechler wrote:
I don't like the name -- I'd prefer getIfExists.  As Baath (2012, R
Journal) pointed out, R names are very inconsistent in naming
conventions, but lowerCamelCase is the most common choice.  Second most
common is period.separated, so an argument could be made for
get.if.exists, but there's still the possibility of confusion with S3
methods, and users of other languages where "." is an operator find it a
little strange.

If you don't like lowerCamelCase (and a lot of people don't), then I
think underscore_separated is the next best choice, so would use
get_if_exists.

Another possibility is to make no new name at all, and just add an
optional parameter to get() (which if present acts as your value.if.not
parameter, if not present keeps the current "object not found" error).

Duncan Murdoch
______________________________________________
R-devel at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel