[R] sapply returning list instead of matrix

S Ellison S.Ellison at lgcgroup.com
Mon Feb 3 10:52:10 CET 2014

> I can read the documentation, I see why it happens, but who in their right
> mind would design a function this way?  
I think you're possibly starting from the wrong perspective, or at least it might be useful to look at it from a different perspective.

In many cases, such as simulations, lapply returns a list of identical-length vectors that, for subsequent purposes, would be more convenient if simplified to a vector or matrix, and that's an extra step or two. sapply is the answer to "wouldn't it be nice if lapply simplified things for me if it were possible?"

Now, if your function does something unexpected and returns uneven lengths, that's actually easier to catch if the return type changes (consider: a function expected to return a length 5 vector could return a length one NA for some input, probably with warning; that would cause the current sapply to return a list and subsequent statements expecting a matrix or vector would grind to a halt. This makes it quite hard for bugs to go undetected.
Forcing sapply to pad to the same length to guarantee an array would hide that, your script would continue to run and you'd be none the wiser until much later. Bugs could _more_ easily get into production code.

And of course, it is pretty much trivial to test for the correct type on return, using is.list etc, so it's a readily trappable behaviour as long as you plan for it.


This email and any attachments are confidential. Any use...{{dropped:8}}

More information about the R-help mailing list