Sigh. I don't agree with this "avoid ifelse because you might not know the 
shape of the arguments" advice. All R variables have shapes and sizes, and the 
better advice is to _pay attention to shapes and sizes_, especially when using 
vectorized functions like ifelse. An easy way to maintain shape/size 
consistency is to work with data frames at the top level of your code.

Which is not to say that I use ifelse liberally... it is not the most efficient 
way to get an answer in many cases. findInterval and cut are often better 
choices, as is in-place modification:

 x <- rep( 2, length( a ) )
 x[ a < 3 ] <- 1

which can be extended if needed.

On July 10, 2019 6:45:55 AM PDT, Eric Berger <ericjber...@gmail.com> wrote:
>Or even
>> a <- 1:5
>> [lots of other code]
>> x <- ifelse( a < 3, 1, 2)
>
>The point (in this example) is that you might have introduced a bug
>because
>you forgot that 'a' is a vector.
>Looking (in isolation) at the assignment to 'x' you believe it's going
>to
>be a single number, either 1 or 2 (unless you know the "shape" of a).
>I've been burned by such issues.
>
>
>On Wed, Jul 10, 2019 at 4:42 PM Eric Berger <ericjber...@gmail.com>
>wrote:
>
>> For example, can you predict what the following code will do?
>> > a <- 1:5
>> > b <- c(2,3)
>> > ifelse( a < 3, 1, b)
>>
>>
>> On Wed, Jul 10, 2019 at 4:34 PM José María Mateos
><ch...@rinzewind.org>
>> wrote:
>>
>>> On Wed, Jul 10, 2019, at 04:39, Eric Berger wrote:
>>> > 1. The ifelse() command is a bit tricky in R. Avoiding it is often
>a
>>> good
>>> > policy.
>>>
>>> You piqued my curiosity, can you elaborate a bit more on this?
>>>
>>> --
>>> José María (Chema) Mateos || https://rinzewind.org
>>>
>>> ______________________________________________
>>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>>> 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]]
>
>______________________________________________
>R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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.

-- 
Sent from my phone. Please excuse my brevity.

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.

Reply via email to