Skip to content
Prev 280980 / 398503 Next

sapply Call Returning " the condition has length > 1" Error

Your puzzle comes from a collision of two somewhat subtle facts that
i) sapply() is a wrapper for lapply(), not apply() and ii)
data.frame()s are secretly columnwise lists. Because of this, sapply =
lapply takes each list element = data.frame column and passes it to
the column individually. Compare this behavior to

lapply(1:4, function(x)  max(x^2))

which converts its not-list input (=c(1,2,3,4)) into a list (=
list(1,2,3,4)) before processing. This is different than
lapply(list(1:4), function(x) max(x^2))

If you want to work element wise, you can work with apply() rather
than sapply(), Vectorize(), or just a plain-ol' for loop.

Does this help?

Michael

PS -- You should nag your collaborator about making a non-vectorized
function. If you got the warning message that started this all off,
there's likely a bug in his code of the if+else vs ifelse variety. If
you've never seen a document called "the R inferno" before, Google it,
and take a look through: it's full of all sorts of helpful
intermediate level tips and these sorts of subtleties are well
documented.
On Tue, Dec 27, 2011 at 4:03 PM, Alex Zhang <alex.zhang at ymail.com> wrote: