[Rd] proposal for "strict" versions of subsetting operators

David Brahm brahm at alum.mit.edu
Tue Oct 28 17:42:16 MET 2003


Tony Plate <tplate at attglobal.net> wrote:
> I'd like to propose adding "strict" versions of the subsetting operators "[",
> "[[", and "$" to the R language.

Interesting idea, Tony!  I think you're addressing 3 somewhat distinct
problems; here's how I deal with them currently:

1) Partial string matching: don't use it, isn't a problem for me.

2) drop=T default: In production code, I try to remember to set drop=F (just as
   I would have to remember to use "$[" under your scheme).  Admittedly I have
   been tripped up a few times.

3) Selective dropping: I have the function g.slice (below).  On 8/23/00 I
   proposed to S-news that drop= could be a logical vector argument, recycled
   as necessary, so that "drop=T" (the default) or "drop=F" are still valid,
   and no code would break.  If I were slightly smarter, I might even know how
   to make g.slice be my array method for "[".

   g.slice <- function(a, ..., drop=TRUE, use.names=TRUE) {
     b <- a[..., drop=FALSE]               # Drop dimensions selectively
     drop <- drop & dim(b)==1              # Recycles "drop" if necessary
     dn <- dimnames(b)
     dimnames(b) <- NULL
     if (sum(!drop) < 2) {                 # Create a vector (or scalar)
       dim(b) <- NULL
       if (use.names) names(b) <- unlist(dn[!drop])
     } else {                              # Create an array
       dim(b) <- dim(b)[!drop]
       if (use.names) dimnames(b) <- dn[!drop]
     }
     b
   }

> Finally, it's worth noting that it would be possible to provide this
> functionality in other ways...  However, code written using subsetting
> functions and/or arguments specifying behavior lacks the conciseness and
> visual scanability of code written using subsetting operators.

At least the selective dropping option (point 3) could be incorporated under
current syntax, fully backward compatible, similar to your version.
-- 
                              -- David Brahm (brahm at alum.mit.edu)



More information about the R-devel mailing list