RFC: enhancement for sapply() : do.names

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Fri, 24 Sep 1999 19:02:00 +0200


Among other uses of  sapply(), I use to use it for 
"analyzing" / "summarizing" components of a list or to `summarize' objects
in my search path,
typically such as

sapply(obj.names, function(n){ r <- get(n); unlist(r[c("x","y","par")]) })

which gives a list or a 3-col matrix (depending if "x", "y","par" have always
same length..) that has no (row)names unfortunately, even though it's clear
that I would want my initial names...

  for(n in 1:3) 
	  assign(paste("o",n,sep=""), list(x=n,y=n^2,par=n/4))
  (obj.n <- paste("o",1:3,sep=""))
  sapply(obj.n, function(n){ unlist(get(n)[c("x","y","par")]) })

which gives

	[,1] [,2] [,3]
    x   1.00  2.0 3.00
    y   1.00  4.0 9.00
    par 0.25  0.5 0.75

but I would want

	  o1  o2   o3
    x   1.00 2.0 3.00
    y   1.00 4.0 9.00
    par 0.25 0.5 0.75

----
I can get this with the following patch :

--- sapply.R	1999/01/29 17:39:28	1.3
+++ sapply.R	1999/09/24 16:12:53
@@ -1,8 +1,10 @@
-sapply <- function(X, FUN, ..., simplify = TRUE)
+sapply <- function(X, FUN, ..., simplify = TRUE, do.names = TRUE)
 {
     FUN <- match.fun(FUN)
-
     answer <- lapply(as.list(X), FUN, ...)
+    if(do.names && is.null(names(answer))) { # create names if sensible
+        if(is.character(X)) names(answer) <- X
+    }
     if(simplify && length(answer) &&
        length(common.len <- unique(unlist(lapply(answer, length)))) == 1) {
 	if(common.len == 1)

---------------

Now, before implementing this:

1) is "do.names" proper naming or should we rather use
	"DO.NAMES", "USE.NAMES", ...
   (at the moment, I'd prefer  USE.NAMES)


2) Inside the new  if(do.names ....) { .... }  clause, 
   we can try harder, e.g.,

  if(do.names && is.null(names(answer))) { # create names if sensible
	names(answer) <- 
	    if(is.character(X)) X  else  abbreviate(deparse(substitute(X)))
  }

   - actually this wouldn't always work as desired;  
     `substitute(X)' would have to be saved
     before the first use of X ( evaluation of expressions...)
   - In that case, do.names (or USE.NAMES) should probably have
     the default  is.character(X)  -- for efficiency & back-compatibility

Opinions?

Martin Maechler <maechler@stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO D10	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._