Skip to content
Prev 280958 / 398503 Next

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

You are right that the problem is that "DummyFunc" isn't vectorized. R
looks for a single logical value in an "if" statement but "x>0" gives
it a whole vector's worth -- as the warning indicates, it only uses
the first and pushes the whole vector through the loop in the
return(-x) branch, which explains the values you saw. The correct way
to do it would be something like:

ifelse(x < 0, -x, x)

If, as you suggest, you can't modify the function (for whatever
reason), you can use the higher-order-function Vectorize() as follows:

vDummyFunc <- Vectorize(DummyFunc)
vDummyFunc(-3:7)

This isn't real vectorization, but it hides some *apply family stuff nicely.

Note that this doesn't act as you might expect on Y since data.frames
are taken column wise by default (you'll get the same problem).

Michael
On Tue, Dec 27, 2011 at 1:14 PM, Alex Zhang <alex.zhang at ymail.com> wrote: