[Rd] Why change data type when dropping to one-dimension?

Jason Vertrees jv at cs.dartmouth.edu
Fri May 29 23:33:47 CEST 2009


First, let me say I'm an avid fan of R--it's incredibly powerful and I
use it all the time.  I appreciate all the hard work that the many
developers have undergone.

My question is: why does the paradigm of changing the type of a 1D
return value to an unlisted array exist?  This introduces boundary
conditions where none need exist, thus making the coding harder and

For example, consider:
  > d = data.frame(a=rnorm(10), b=rnorm(10));
  > typeof(d);			# OK;
  > typeof(d[,1]);  		# Unexpected;
  > typeof(d[,1,drop=F]);	# Oh, now I see.

This is indeed documented in the R Language specification, but why is it
there in the first place?  It doesn't make sense to the average
programmer to change the return type based on dimension.

Here it is again in 'sapply':
  > sapply
  > function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
  > {
  >	[...snip...]
  >        if (common.len == 1)
  >            unlist(answer, recursive = FALSE)
  >        else if (common.len > 1)
  >            array(unlist(answer, recursive = FALSE),
  >			dim = c(common.len,
  >                length(X)), dimnames = if (!(is.null(n1 <-
  >			names(answer[[1]])) &
  >                is.null(n2 <- names(answer))))
  >                list(n1, n2))
  >	[...snip...]
  >  }

So, in 'sapply', if your return value is one-dimensional be careful,
because the return type will not the be same as if it were otherwise.

Is this legacy or a valid, rational design decision which I'm not yet a
sophisticated enough R coder to enjoy?


-- Jason


Jason Vertrees, PhD

Dartmouth College : jv at cs.dartmouth.edu
Boston University : jasonv at bu.edu

PyMOLWiki : http://www.pymolwiki.org/

More information about the R-devel mailing list