Hey thanks for the helpful snark, Bert.
To everyone else, I apologize for neglecting to actually include the
examples.
a <- function(i) { list(1) }
b <- function(i) { list(1,2) }
ll <- sapply(seq(3), a, simplfy="list")
mm <- sapply(seq(3), b)
class(ll)
class(mm)
> class(ll)
[1] "list"
> class(mm)
[1] "matrix"
I can read the documentation, I see why it happens, but who in their right
mind would design a function this way? Can you imagine how many bugs are
lurking because people haven't yet hit the right set of input that is going
to cause sapply() to return a list instead of a matrix().
The point is that having the type of return value depend on the length of
output from the applied function is simply madness. It is a terrible
design decision. What is to be gained from the fact that I have to test
the type of value returned from sapply()? I was hoping plyr::laply()
would be better but it perpetuates the same bad interface.
[so sorry for sending html, if that is what's happening. I guess gmail
send html by default? ]
On Fri, Jan 31, 2014 at 1:44 PM, Bert Gunter wrote:
> As you ignored the posting guide and posted in HTML, your "below"
> didn't get through. So one can only guess that it has something to do
> with (see ?sapply)
>
> "Simplification in sapply is only attempted if X has length greater
> than zero and if the return values from all elements of X are all of
> the same (positive) length. If the common length is one the result is
> a vector, and if greater than one is a matrix with a column
> corresponding to each element of X. "
>
> Return values most also be of the same type, also, obviously.
>
> Cheers,
> Bert
>
> Bert Gunter
> Genentech Nonclinical Biostatistics
> (650) 467-7374
>
> "Data is not information. Information is not knowledge. And knowledge
> is certainly not wisdom."
> H. Gilbert Welch
>
>
>
>
> On Fri, Jan 31, 2014 at 1:36 PM, chris warth wrote:
> > Can anyone suggest a rationale for why sapply() returns different types
> > (list and matrix) in the two examples below? Is there any way to get
> > sapply() or any other apply() function to return a matrix in both cases?
> > simplify=TRUE doesn't change the outcome.
> >
> > I understand why it is happening, I just can't understand why such
> > unpredictable behavior makes sense.
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help@r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]